Fetch data once with Observables in Angular 2

前端 未结 4 1976
旧时难觅i
旧时难觅i 2020-12-29 12:32

I have a service, what is used several times from a lot of my Angular 2 components. It fetches customer data from a Web API and returns an Observable:

getCus         


        
4条回答
  •  盖世英雄少女心
    2020-12-29 12:34

    If you want multiple children to subscribe to the same observable, but only execute the observable once you can do the following.

    Note that this does adhere to the design of observables since we are executing the observable in the service layer (Observable.fromPromis(stream.toPromise()) when execution should be done from the component subscribing. View https://www.bennadel.com/blog/3184-creating-leaky-abstractions-with-rxjs-in-angular-2-1-1.htm for more.

      //declare observable to listen to
      private dataObservable: Observable;
    
      getData(slug: string): Observable {
    
        //If observable does not exist/is not running create a new one
        if (!this.dataObservable) {
    
            let stream = this.http.get(slug + "/api/Endpoint")
                .map(this.extractData)
                .finally(() => {
                    //Clear the observable now that it has been listened to
                    this.staffDataObservable = null;
                });
    
            //Executes the http request immediately
            this.dataObservable = Observable.fromPromise(stream.toPromise());
    
        }        
    
        return this.staffDataObservable;
     }
    

提交回复
热议问题