Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 & RxJS - caching a service that takes a parameter

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.

like image 695
kevfuzz Avatar asked Apr 13 '17 11:04

kevfuzz


People also ask

Should I learn AngularJS or Angular 2?

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.

How old is Angular 2?

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.

What is Angular 2 architecture?

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.


1 Answers

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);
}
like image 60
n00dl3 Avatar answered Nov 16 '22 01:11

n00dl3