Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http service cache

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.

like image 561
user990993 Avatar asked Dec 10 '22 11:12

user990993


1 Answers

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();
        }
    }
like image 135
CharanRoot Avatar answered Dec 13 '22 23:12

CharanRoot