I'm trying to add caching to an Angular2 HTTP service and just can't seem to figure it out.
I followed other posts and have it working perfectly for HTTP services that don't take any parameters e.g.
workSummaries = this.http.get('http://locahost:8080/teams')
.map((response: Response) => response.json())
.publishReplay(1, 3000)
.refCount()
.take(1);
However I'm lost in trying to figure out can I make above work when I introduce a teamId parameter that should be sent with the request.
So ideally if the same teamId has been used in the last X seconds just read from the cache else if it's a new teamId or 3 seconds has past then call the service.
Any help would be great.
Thanks, Kevin.
Angular 2 is more useful for developing mobile applications and includes higher performance speeds than AngularJS. JavaScript is easier to understand than TypeScript, making Angular 2 a more advanced and challenging framework for developers to use.
Angular 2 moved to Beta in December 2015, and the first release candidate was published in May 2016. The final version was released on September 14, 2016.
Architectural Overview Angular is designed to be modular, an Angular 2 app comprises of several components, which are connected via routing or selectors, these components may have templates attached to it which may display component properties and attach events to interact with the properties.
You can use a Map to maintain the teamID/team association (I didn't touch the Observable creation part):
summaries = new Map < number, Observable < Team >> ();
getTeam(id: number) {
if (!this.summaries.get(id)) {
let team = this.http.get('http://locahost:8080/teams/' + id)
.map((response: Response) => response.json())
.publishReplay(1, 3000)
.refCount()
.take(1);
this.summaries.set(id, team)
}
return this.summaries.get(id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With