Sometimes, we want to share the result of an Angular Http network call in Rxjs 5.
In this article, we’ll look at how to share the result of an Angular Http network call in Rxjs 5.
How to share the result of an Angular Http network call in Rxjs 5?
To share the result of an Angular Http network call in Rxjs 5, we can create our own service.
For instance, we write
@Injectable()
export class HttpCache {
constructor(private http: Http) {}
get(url: string): Observable<any> {
let cached: any;
if (cached === sessionStorage.getItem(url)) {
return Observable.of(JSON.parse(cached));
} else {
return this.http.get(url).map((resp) => {
sessionStorage.setItem(url, resp.text());
return resp.json();
});
}
}
}
to create the HttpCache
service class that has the get
method.
In get
, we check if we stored the response in session storage.
If it is, then we return an observable that has the cached result.
Otherwise, we call this.http.get
to make a GET request to the url
.
And we call sessionStorage.setItem
to store the response once we have it.
Conclusion
To share the result of an Angular Http network call in Rxjs 5, we can create our own service.