Demo
Service
HTML
TS
SCSS
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 observableusers$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.
Basic Usage
| ID | Name | |
|---|---|---|
| 1 | Leanne Graham | Sincere@april.biz |
| 2 | Ervin Howell | Shanna@melissa.tv |
| 3 | Clementine Bauch | Nathan@yesenia.net |
| 4 | Patricia Lebsack | Julianne.OConner@kory.org |
| 5 | Chelsey Dietrich | Lucio_Hettinger@annie.ca |
| 6 | Mrs. Dennis Schulist | Karley_Dach@jasper.info |
| 7 | Kurtis Weissnat | Telly.Hoeger@billy.biz |
| 8 | Nicholas Runolfsdottir V | Sherwood@rosamond.me |
| 9 | Glenna Reichert | Chaim_McDermott@dana.io |
| 10 | Clementina DuBuque | Rey.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.
