Home > OS >  Angular http cache in pipe
Angular http cache in pipe

Time:12-26

I'm trying to add a simple caching system to my HTTP request in my service. here is my plan which is not succeed yet. first, call the service and then store response into one collection like array or subject and if next time service call instead of reading from the server, read it from my array or subject that stored that response. I want to use this service inside one PIPE which returns one string from the object. But for some reason ignore my condition.

My Source Code

CodePudding user response:

this happends because your tap logic that contains all the caching logic is evaluated after the response comes, but in your application you make 4 such method calls from the very beginning. to fix that I propose to store observables, not their results (because you have the observable on the moment of the call) and to share the result shareReplay operator can be used.

  readedPlatformsCache: Record<number, Observable<IPlatform>> = {};

  getPlatforms(id: number): Observable<IPlatform> {
    const cachedPlatform = this.readedPlatformsCache[id];

    if (!cachedPlatform) {
      const request = this._http.get<any>('assets/platforms.json').pipe(
        tap(() => console.log('http called')),
        map((platforms: IPlatform[]) => platforms.find((p) => p.id === id)),
        shareReplay(1),
      );
      return this.readedPlatformsCache[id] = request;
    } else {
      return cachedPlatform;
    }
  }
  • Related