Home » Headline, Software Development

RxJS – Caching http requests

31 May 2017 No Comment

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';

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())
    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() {
        (data:any) => {
          this.myComponentData = data;
         error => {
           if(error.status === 404) {}

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image