Home > Enterprise >  How to avoid refetching data if parameters don't change in Angular
How to avoid refetching data if parameters don't change in Angular

Time:11-10

I have this function on a service that get details about a physical store :

public getStoreDetails(storeName?: string, origin?:string): Observable<E2StoreFinderStore> {
    console.log('getStoreDetails', storeName, origin);
    const api = this.OCC.getUrl(`/stores/details/name/${storeName}`);
    let params = new HttpParams();
    return this.http
      .get<E2StoreFinderStore>(api, {
        responseType: 'json',
        params: params.append('fields', 'FULL').append('type', 'POS'),
      })
      .pipe(catchError(this.handleErrorService.handleError));
  }

this function is being called by 4 different components, but they are all using the same storeName, so they're basically fetching the same data from the API 4 times. I was wondering how can I avoid refetching this data if the storeName parameter hasn't changed from the last time it was called.

For example, on the first time getStoreDetails is called it would store the data retrieved and on the subsequent times it is called if the storeName parameter is the same as before it would just return the stored data instead of running the API call.

CodePudding user response:

You can do something like that:

dataLoaded: {[key: string]: E2StoreFinderStore }= {};
public getStoreDetails(storeName?: string, origin?:string): Observable<E2StoreFinderStore> {
  if(!this.dataLoaded[storeName]) {
    console.log('getStoreDetails', storeName, origin);
    const api = this.OCC.getUrl(`/stores/details/name/${storeName}`);
    let params = new HttpParams();
    return this.http
      .get<E2StoreFinderStore>(api, {
        responseType: 'json',
        params: params.append('fields', 'FULL').append('type', 'POS'),
      })
      .pipe(
        tap(res => { this.dataLoaded[storeName] = res }),
        catchError(this.handleErrorService.handleError)
      );
  } else {
    return new Observable((observer) => {
      observer.next(this.dataLoaded[storeName]);
      observer.complete();
    });
  }
}

I provide some code at https://stackblitz.com/edit/angular-ivy-3zz8uq

  • Related