DEV Community

Ariel Gueta
Ariel Gueta

Posted on

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.

Top comments (1)

Collapse
 
sefatanam profile image
Sefat Anam

Did you implement it with Interceptor instead of using in service ?