Friday, December 6, 2019

Angular 2+ how to share same ajax response with multiple components


import { from, Observable } from 'rxjs';
import { share, shareReplay } from 'rxjs/internal/operators';
export class HeaderService {
public profileObservable;
constructor(
private http: HttpClient) {
}
getProfile(): Observable {
if (this.profileObservable) {
return this.profileObservable;
} else {
this.profileObservable = this.http.get(environment.APIEndpoint + 'userProfile').pipe(shareReplay());
this.profileObservable.subscribe(res = & gt; this.setUserProfileData(res));
return this.profileObservable;
}
}
}
view raw gistfile1.txt hosted with ❤ by GitHub




Create a service like above.
The line

import shareReplay  from rxjs

import { share, shareReplay } from 'rxjs/internal/operators'; 


this.profileObservable =

this.http.get(environment.APIEndpoint + 'userProfile').pipe(shareReplay());


create a shareable HTTP Observable. This can used by any component to get the response.

Only one ajax request will trigger for all the request to this service.