javascript - Fetch data once with Observables in Angular 2 -


i have service, used several times lot of angular 2 components. fetches customer data web api , returns observable:

getcustomers() {    return this.http         .get(this.baseuri + this.url)         .map((r: response) => {             let = r.json() customer[];                                    return a;                                  });                }     

i inject service in root component, , in every component wants access customers subscribe observable:

this.customerservice.getcustomers().subscribe(v => this.items = v); 

however, every component subscribes observable causes execution of http-request. fetch data once enough. if try share(), not solve problem:

getcustomers() {    return this.http         .get(this.baseuri + this.url)         .map((r: response) => {             let = r.json() customer[];                                    return a;                                  }).share();                }    

still same issue. proposals operators have use fetch data once?

you can save downloaded data in service:

someservice {   private customers: array<customer>;    constructor(public http: http) {}    public getcustomers(): observable<array<customer>> {     return new observable(observer => {         if (this.customers) {             observer.next(this.customers);             return observer.complete();         }         this.http             .get(this.baseuri + this.url)             .map((r: response) => (r.json() array<customer>))             .subscribe((customers: array<customer>) => {                 this.customers = customers;                 observer.next(this.customers);                 observer.complete();             });     }); } 

and then:

this.customerservice.getcustomers()     .subscribe(customers => this.customers = customers); 

however, more complex usages i'd take advantage of rxjs's replaysubject (saved in class variable) cache downloaded data , prevent making 2 requests @ same time using additional variable in method taking parameter responsible reload. approach allows me up-to-date data in place of application.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -