How to reuse angular observable across multiple components? (To avoid having to duplicate a request twice?)

后端 未结 3 1979
心在旅途
心在旅途 2021-01-06 01:00

I have a service \"MyHttpService\" that includes an observable like this:

grabData() {
return this.http.get(\'myaddress\')
                         .map((res         


        
3条回答
  •  余生分开走
    2021-01-06 01:37

    You can use the share operator to make an observable multicast. This is also relevant within a single component as multiple async bindings to the same osbervable will cause multiple requests to be made. There is a good ng-conf talk here that covers the issue.

    import 'rxjs/add/operator/share';
    
    grabData() {
      return this.http.get('myaddress')
                      .map((res:Response) => {return res.json()})
                      .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
                      .share(); 
    }
    

提交回复
热议问题