Hi Dixit,
use a service to do the actual http get, and inject that into all your
services.
Here is a quick sample to get you going:
import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { HttpClient } from '@angular/common/http';
import { shareReplay,switchMap } from 'rxjs/observables';
@Injectable()
export class LoadDataService implements OnDestroy {
private refresh$ = new Subject<void>();
public data$ = this.refresh$
.asObservable()
.pipe(
// do the actual http get action
switchMap($ => this.http.get('someUrl')),
// buffer the result, and make it 'hot'
shareReplay(1)
);
/**
* a sharable like the above will loose it's content after the
* last subscriber unsubscribes. However, we want to keep it
* for the entire time the program runs. simple solution
* is to keep a subscription open in the service itself.
*/
//
private subscription = this.data$.subscribe();
constructor(private http: HttpClient) {}
/**
* purge the cache by restarting the request.
* All subscribers to data$ will get in fresh copy
*/
refresh() {
this.refresh$.next();
}
ngOnDestroy() {
// clean up the subscription.
this.subscription.unsubscribe()
}
}
hope this helps,
Regards
Sander
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.