RxJS – Caching http requests
May 31, 2017
Caching is important for performance, especially on mobiles and slow networks. In this article I will show how to cache http calls using rxjs observables.
The below code is using Angular 4 and is in an Injectable service named SettingsService.
const settingsUrl = '/api/settings';
@Injectable()
export class SettingsService {
// define cache variable
private cache: any;
// include
constructor(private http: Http) {}
get() {
if (!this.cache) {
this.cache = this.http.get(settingsUrl)
.map((res: Response) => res.json())
.publishReplay(1)
.refCount()
.catch(this.handleError);
}
return this.cache;
}
// handle error
private handleError (error: any) {
return Observable.throw(error);
}
// clear cache
clear() {
this.cache = null;
}
The above service can then be subscribed in multiple components, the first call will be be server based and other subsequent calls will be from the cache.
I have added a clear() function that clears the cache for server based calls.
Below is the code that can be used in Components for subscribing to the above SettingsService.
...
constructor(private settingsService: SettingsService) {}
ngOnInit() {
this.settingsService.get()
.subscribe(
(data:any) => {
this.myComponentData = data;
},
error => {
if(error.status === 404) {}
}
);
}
}
...
