Angular2和RxJS-缓存带有参数的服务

kev*_*uzz 5 caching rxjs angular

我正在尝试将缓存添加到Angular2 HTTP服务中,但似乎无法弄清楚。

我关注了其他帖子,并使其完全适用于不带任何参数的HTTP服务,例如

workSummaries = this.http.get('http://locahost:8080/teams')
            .map((response: Response) => response.json())
            .publishReplay(1, 3000)
            .refCount()
            .take(1);
Run Code Online (Sandbox Code Playgroud)

但是,当我引入应该与请求一起发送的teamId参数时,我迷失了方向,无法确定是否可以进行上述工作。

因此,理想的情况是,如果在最近X秒钟内使用了相同的teamId,则只需从缓存中读取,否则,如果它是新的teamId或已经过了3秒钟,则调用该服务。

任何帮助都会很棒。

谢谢,凯文。

n00*_*dl3 6

您可以使用Map来维护teamID / team关联(我没有触摸Observable创建部分):

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);
}
Run Code Online (Sandbox Code Playgroud)