Extending Angular 2 Observables based service to return data from local Storage.
In previous blog post I have demonstrated using HTML 5 local storage to store data and if not found, service will hit the API end point to fetch data, but I was using the promise approach.
I know these are pretty basic code snippets, but could save me hours if I have documented them – so here I am documenting.
I have manage to do the same thing using the Observerbles ,below is the code snippet for every ones reference.
getAll(): Observable<IncomeSourceType[]> { let types: IncomeSourceType[] = this.storageService.get('IncomeSourceType'); if (types != null) { return Observable.of(types); } return this.http.get(this.apiUrl) .map((response) => { let types: IncomeSourceType[] = response.json(); this.storageService.save('IncomeSourceType', types); this.extractData(response); }) .catch(this.handleError); }