Last active
August 29, 2018 03:40
-
-
Save saptarshibasu/0306d58be3cc16bf04ab4a93b2ae232e to your computer and use it in GitHub Desktop.
[Caching API Response Using RxJS] Sometimes REST API is called to fetch static data (e.g. a list of all countries, states etc.) from the server. Such API response should be cached to avoid any future call to the API and thus improving performance. In the following code, shareReplay RxJS operator is used to cache the last api response and return …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { retryWhen, delay, tap, scan, concatMap, shareReplay, share } from 'rxjs/operators'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class PostService { | |
private posts; | |
public getPosts() { | |
if (!this.posts) { | |
this.posts = this.http.get("https://jsonplaceholder.typicode.com/posts") | |
.pipe( | |
retryWhen(err => err.pipe( | |
scan( | |
(retryCount, err) => { | |
if (retryCount > 2) | |
throw err; | |
else | |
return retryCount + 1; | |
}, 0 | |
), | |
delay(1000), | |
tap(err => console.log("Retrying...", err)) | |
)), | |
shareReplay(1) | |
); | |
} | |
return this.posts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment