Angular library for storing HttpResponse on navigator memory
npm install ngx-request-cacheCache for HTTP requests with Angular HttpClient.
Common usages:
* Avoid hitting server to fetch same data when service is invoked serially or in parallel.
* Create offline application.
Library relies on ensure requests go through Angular HttpInterceptor (default behavior).
``bash`
npm i ngx-request-cacheUsage
* Setup root module:
`javascript
import { NgxRequestCacheModule } from 'ngx-request-cache';
@NgModule({
imports: [ NgxRequestCacheModule ]
})
`
By default, persistence is on memory. To switch to sessionStorage or localStorage, review here.
* Cache an API:
`javascript
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequestCacheHeader } from 'ngx-request-cache';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getData(): Observable
let headers = new HttpHeaders();
headers = headers.append(RequestCacheHeader.Cachable, '');
return this.http.get(URL, { headers });`
}
}
Library's headers are removed before sending the request to the server.
* Clear cache:
`javascript
import { RequestCacheService } from 'ngx-request-cache';
export class DataService {
constructor(private requestCacheService: RequestCacheService) {
this.requestCacheService.clear(); // All data stored.
}
}
`
Cache store with persistence into sessionStorage:
`javascript`
@NgModule({
imports: [
NgxRequestCacheModule.forRoot({ store: 'sessionStorage' })
]
})
Cache store with persistence into localStorage:
`javascript`
@NgModule({
imports: [
NgxRequestCacheModule.forRoot({ store: 'localStorage' })
]
})