I'm trying to implement caching in Angular application for http service.
My code in service countriesService
public get(): Observable<any> {
return this.http.get(`/countries`, {})
.map(res => res.json())
.publishReplay(1)
.refCount();
}
In component CountriesComponent, I have
ngOnInit() {
this.countriesService.get()
.subscribe(res => {
this.countries = res.countries;
});
}
I'm loading component in route config
const appRoutes: Routes = [
{ path: 'countries', component: CountriesComponent },
{ path: 'cities', component: CitiesComponent },
];
Every time I returning from cities to countries, I see a request to => /countries. It shouldn't fire request as it should be cached(that's how it's working in angular 1.x with promises), but not with angular 4 and rxJs.
you can save countries in service for first time after that you can re use Service variable.
public get(): Observable<any> {
if(this.countries != null)
{
return Observable.of(this.countries );
}
else
{
return this.http.get(`/countries`, {})
.map(res => res.json())
.do(countries => this.countries = countries )
.publishReplay(1)
.refCount();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With