Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - Angular2 observable share is not working

Angular2 Observable share is not working and duplicate http calls going

BuildingService.ts

@Injectable()
export class BuildingService {

constructor(private http: Http){       
  }

buildings$: Observable<Building[]>;
this.buildings: Building[];

getData() : Observable<Building[]>{
     this.buildings$ = this.http.get('http://localhost:8080/buildings').share().map(this.extractData);
     this.buildings$.subscribe(buildings => this.buildings = buildings);
     return this.buildings$;
  }

 private extractData(res: Response) {
    let body = res.json();
    return body;
} 

}

component1.ts

export class component1 {
constructor( private  buildingService: BuildingService) {}

this.subscription = this.buildingService.getData()
            .subscribe(buildings => console.log(buildings),
            error =>  this.errorMessage = <any>error);
}

component2.ts

export class component2 {
constructor( private  buildingService: BuildingService) {}

this.subscription = this.buildingService.getData()
            .subscribe(buildings => console.log(buildings),
            error =>  this.errorMessage = <any>error);
}

share is not working, multiple http calls are going. Even I tried code from this link

but no use.

Can somebody please let me know how to avoid duplicate http calls with Angular Observable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this is just misunderstanding of what share() does.

When you call this.buildings$.subscribe(...) it makes a ConnectableObservable thanks to share() operator which is immediately followed by connect().

If you make another subscription while the HTTP request is pending it will just add another Observer to the ConnectableObservable and when the response is ready it'll be sent to both Observers. However if you let this.buildings$ to complete and after that you subscribe again it'll make another HTTP request because the ConnectableObservable is not connected to its source.

What you want instead is .publishReplay(1).refCount() (or shareReplay(1) since RxJS 5.4.0) that replays the last item emitted from the source. Very likely you'll also want to append take(1) to properly complete the chain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...