DEV Community

Cover image for How to cache requests in Angular
Pedro Bruneli
Pedro Bruneli

Posted on

How to cache requests in Angular

Table contents

Purpose

In our application, users often revisit the same path/page multiple times. Each time a user returns to the page, the application makes another API call. However, why do we call the same API path every time the user returns to the page instead of saving the request and reusing it?

Pros:

  • Saving API resources (fewer calls, lower cost)
  • Eliminating repetitive loaders every time the user enters the page

What?

To achieve this, we utilize the shareReplay method in RxJS. According to the documentation, shareReplay replays the result of an Observable as many times as needed.

How?

Implementing it is straightforward. All you need to do is add the shareReplay pipe to the Observable, as shown in the code below:

  public getFacts() {
      return this.httpClient.get<Fact[]>('https://cat-fact.herokuapp.com/facts')
      .pipe(shareReplay());
  }
Enter fullscreen mode Exit fullscreen mode

Now you're all set. Simply use the method, and the pipe will handle everything for you.

Seeing the change

Let's compare the difference between using shareReplay and not using it.

Without using it:

Image of code making 2 http calls

Notice that every time I click "Call subscriber" my code makes an HTTP call and returns the cat facts.

However, since my API changes daily rather than constantly, let's add shareReplay and observe the result:

Image of code making no http calls after using shareReplay method

See? When I clicked "Call subscriber", it returned the same result without making any additional HTTP calls!

Conclusion

RxJS is a powerful tool, and with just a simple line of code, your performance could be significantly improved.

Cheers!!!

Top comments (2)

Collapse
 
rajanchavda profile image
Rajan Chavda

How to clear cache at certain time interval ?

Collapse
 
pedrobruneli profile image
Pedro Bruneli • Edited

In that case you can do the share method.
e.g:

this.httpClient
      .get<Facts[]>('https://cat-fact.herokuapp.com/facts')
      .pipe(
        share({
          connector: () => new ReplaySubject(1),
          resetOnComplete: () => timer(5000),
          resetOnError: true,
}),
);
Enter fullscreen mode Exit fullscreen mode

We use the replaySubject as connector.
If api throws an error we reset it immediatly, otherwise we wait the timer subject to finish and resets it!

Regards