Reputation: 155
I am a newbie to angular 2 and Observable.
I have a function getCurrentUserDetails()
as service, which returns an observable with the details of current user. I am using this on every route access.
I want to limit my http request to database each time i access this function.
I want to create a function which returns the data if available else create a http request get the data and return that data.
Below is the code which i tried:
private currentUser: any;
getCurrentUserDetails(){
if(!this.currentUser){
this.currentUser = this._http.get('getcurrentuserdetails').map((res:Response) => res.json()).share();
return this.currentUser;
}
else {
return this.currentUser;
}
}
Upvotes: 1
Views: 89
Reputation: 96891
I guess you want to do something like this instead of the share()
operator:
publishReplay()->refCount()->take(1)
This means that every time you subscribe to this Observable you'll receive the cached value and the take(1)
operator will make the chain complete immediately without subscribing to the source and causing more HTTP requests.
Upvotes: 1