I have a function that loads user details and returns an observable. This function is called from multiple places, but I want to prevent redundant calls by waiting until the result is loaded after the first call. Can anyone suggest how this can be accomplished using RxJs and Angular?
getUser(): Observable<any> {
return this.http.get('/userAuthenticated');
}
One approach is to wait for the first call to complete and then save the result in a static variable:
getUser(): Observable<any> {
if(!this.userIsLoading) {
this.userIsLoading = true;
return this.http.get('/userAuthenticated').pipe(
tap((res: any) => {
this.userIsLoading = false;
this.User = res.data;
}));
} else {
// Wait for the first call to complete
return of(this.User);
}
}
Another idea is to define a static variable for the observable.
Any help would be appreciated.