Example 2: HTTP caching with RxJS shareReplay

Efficiently cache HTTP requests in a service using shareReplay for blazing-fast, network-friendly Angular apps.

How does the caching work?

  • Check cache:getUsers() checks if a cached observable users$ exists.
  • First request: If not, it performs an HTTP GET and pipes the result through shareReplay(1).
  • Share result:shareReplay(1) ensures all subscribers share the same HTTP response and only one network request is made.
  • Reuse: The observable is stored in the service, so repeated calls return cached data without new HTTP requests.
  • Refresh: Clicking Refresh Users will re-invoke getUsers() and demonstrate the cache in action.
Why use shareReplay? It is ideal for caching HTTP responses in Angular services, especially for data that doesn't change often.
Prevents duplicate network calls and improves performance for your users.

Basic Usage

IDNameEmail
1Leanne GrahamSincere@april.biz
2Ervin HowellShanna@melissa.tv
3Clementine BauchNathan@yesenia.net
4Patricia LebsackJulianne.OConner@kory.org
5Chelsey DietrichLucio_Hettinger@annie.ca
6Mrs. Dennis SchulistKarley_Dach@jasper.info
7Kurtis WeissnatTelly.Hoeger@billy.biz
8Nicholas Runolfsdottir VSherwood@rosamond.me
9Glenna ReichertChaim_McDermott@dana.io
10Clementina DuBuqueRey.Padberg@karina.biz

Key Features

  • ⚡ Efficient HTTP caching with shareReplay
  • 🔄 Single network request reused by all subscribers
  • 🚀 Great for data that rarely changes
  • 🧩 Simple, service-based implementation

This example uses shareReplay(1) to cache the HTTP response and share it across all consumers.