Caching HTTP Response in Angular with Cashew

arielgueta

Ariel Gueta

Posted on March 1, 2020

Caching HTTP Response in Angular with Cashew

Cashew is a new library that provides seamless caching for HTTP responses in Angular.

Installation

npm install @ngneat/cashew

Usage

Inject the HttpCacheInterceptorModule module along with HttpClientModule in AppModule:

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpCacheInterceptorModule } from '@ngneat/cashew';

@NgModule({
  imports: [HttpClientModule, HttpCacheInterceptorModule.forRoot()],
  bootstrap: [AppComponent]
})
export class AppModule {}

And that's all. Now we can use the withCache function for any request we want to cache:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { withCache } from '@ngneat/cashew';

@Injectable()
export class TodosService {
  constructor(private http: HttpClient) {}

  getUsers() {
    return this.http.get('todos', withCache());
  }
}

Local Storage Support

The library also supports caching in localstorage:

import { HttpCacheInterceptorModule, useHttpCacheLocalStorage } from '@ngneat/cashew';

@NgModule({
  imports: [HttpClientModule, HttpCacheInterceptorModule.forRoot()],
  providers: [useHttpCacheLocalStorage],
  bootstrap: [AppComponent]
})
export class AppModule {}

For more information, check out the docs.

💖 💪 🙅 🚩
arielgueta
Ariel Gueta

Posted on March 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related