1

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

1 Answer 1

2

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;
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, this solves my problem. but I don't understand what is the problem with my code not working. Even if I check readedPlatforms before observable nothing happened and got undefined. and another problem is not understanding when the return of(), platform.pipe.ts file even gets the object return null to HTML template and not working.
lets say your API takes a second to return you a response and I ll try to desctibe how it worked without fix. You call method with id 1. it immediately checks if item 1 is cached. It is not. So it makes a request. then again, method is called with id 1. it is not in cache - the request is made. the second passes.... first request is returned. item 1 is stored in the cache. and the second request is also returned, and item 1 is got overwritten in the cache by the exact same item. By storing observable in the cache we immediately fill it, not after the response is got

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.