How to cache API responses in Angular
Caching API responses reduces unnecessary network requests, improves application performance, and provides better user experience.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented caching strategies in Angular applications throughout my 11 years of framework development.
The most effective approach is using the RxJS shareReplay operator in your services to cache observable responses.
This method automatically shares cached data across multiple subscribers and reduces API calls.
Use the shareReplay operator to cache HTTP responses in Angular services.
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs'
import { shareReplay } from 'rxjs/operators'
@Injectable({ providedIn: 'root' })
export class DataService {
private cache$: Observable<any>
constructor(private http: HttpClient) {}
getData(): Observable<any> {
if (!this.cache$) {
this.cache$ = this.http.get('/api/data').pipe(
shareReplay(1)
)
}
return this.cache$
}
clearCache(): void {
this.cache$ = null
}
}
Here the service stores the cached observable in a private property. The shareReplay(1) operator replays the last emitted value to new subscribers without making additional HTTP requests. If the cache doesn’t exist, it creates a new request and caches the result. The clearCache method allows manual cache invalidation when needed.
Best Practice Note:
This is the same caching pattern we use in CoreUI Angular components for reference data and configuration.
For time-based cache expiration, combine shareReplay with timer and switchMap, and consider using HTTP interceptors for application-wide caching strategies.



