angularcachingrxjs

Caching multiple APIs with RxJS in Angular


I have a component with multiple tabs, where users can go back and forth. I need to load the data from the backend in the first tab. This creates unnecessary HTTP calls each time component 1 is re-initialized. My idea is to make the caching service in which I would store the result of the HTTP Call and when the component is re-initialized, it will get data from the service (not from the backend).

Here are some other requirements:

It somehow starts working until I add Subject for triggering the first load. Now, it is triggering an HTTP call every time component 1 is re-initialized. Stackblitz demo

Any help is appreciated! Thanks


Solution

  • The reason your code is fetching every time you load Component A, is because you call triggerLoad$.next() each time Component A initializes!

    You don't actually need a separate trigger, you can simply declare a single codetables$ observable that both fetches and caches the data.

      readonly codetables$ = from(this.codetableTypes).pipe(
        mergeMap(codetableType => this.getCodetable(codetableType)),
        scan((acc, current) => ({...acc, ...current}), {} as CodetableOptions),
        shareReplay(1),
        takeUntilDestroyed()
      );
    

    Here we use shareReplay to cache the value. It behaves like a ReplaySubject(1); when consumers subscribe, they will receive the latest value immediately.

    Here's a working Stackblitz