angular 4 caching using localstorage and rxjs operator
In this blog , I am discussing a very important feature implementation in angular that may improve the performance of angular application. For example if we are getting data from web api using httpclient module repeatedly which increase server round trips that may cause of performance downgrade.
Caching in angular may be implemented by various techniques for example.
- local storage
- session storage
- startWith rxjs operator
In this example I will use localstorage and startWith operator and github api repository.
github repository URL :https://api.github.com/search/repositories?q=angular
Step1: Create new component and pass reference of it into app.component.html
ng g c cachingex
Step2: Write following code into cachingex component.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {map , startWith} from 'rxjs/operators'; const CACHE_KEY = "httprepocache"; @Component({ selector: 'app-cachingex', templateUrl: './cachingex.component.html', styleUrls: ['./cachingex.component.css'] }) export class CachingexComponent implements OnInit { repos; constructor(private http : HttpClient) { const path='https://api.github.com/search/repositories?q=angular'; this.repos = http.get<any>(path).pipe(map(data => data.items)); /*this.repos.subscribe(next =>{ localStorage[CACHE_KEY] = JSON.stringify(next) } );*/ this.repos = this.repos.pipe(startWith(JSON.parse(localStorage[CACHE_KEY] || '[]'))); } ngOnInit() { } }
cachingex.component.html
<h1>Fast Caching ex </h1> <div *ngFor="let repo of repos | async"> <h2>{{repo.name}}</h2> <div>{{ repo.description | json}}</div> </div>
Step 3: Pass reference of HttpClient into cachingex component.ts and app.module.ts
import { HttpClient } from ‘@angular/common/http’;
app.module.ts
Step 4: Run program.
ng serve –open
Output: