Http Service Cache

I am trying to implement caching in an Angular application for the http service.

My code in countriesService

  public get(): Observable<any> {
    return this.http.get(`/countries`, {})
      .map(res => res.json())
      .publishReplay(1)
      .refCount();
  }

In the Component Country component I have

  ngOnInit() {
    this.countriesService.get()
      .subscribe(res => {
        this.countries = res.countries;
      });
  }

I load the component into the route configuration

const appRoutes: Routes = [
  { path: 'countries', component: CountriesComponent },
  { path: 'cities', component: CitiesComponent },
];

Every time I return from cities to countries, I see a request => / countries. It should not run the request because it must be cached (that it works in Angular 1.x with promises), but not with Angular 4 and rxJs.

+4
source share
1 answer

you can first save the countries in the service, after which you can reuse the 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();
        }
    }
+12
source

Source: https://habr.com/ru/post/1679828/


All Articles