Angular 按角度中的唯一Id进行缓存

Angular 按角度中的唯一Id进行缓存,angular,caching,rxjs,Angular,Caching,Rxjs,我想在Angular中实现缓存。我有两个方法GetAll()和GetById(id:number,如下所示) 对于GetAll(),我实现了缓存,它工作正常 private cache$: Observable<any>; getAll() { if (!this.cache$) { this.cache$ = this.getAll().pipe( shareReplay(1) ); } return this.cache$; } } 显然,我

我想在Angular中实现缓存。我有两个方法GetAll()和GetById(id:number,如下所示)

对于GetAll(),我实现了缓存,它工作正常

private cache$: Observable<any>;
getAll() {
  if (!this.cache$) {
     this.cache$ = this.getAll().pipe(
     shareReplay(1)
   );
 }
 return this.cache$; 
}
}

显然,我不想预先基于Id创建缓存$


如何在angular中执行此操作?

您可以创建一个字典,以按id保留所有缓存的观察值:

cacheMap = {}

getById(id: number) {
  if (!this.cacheMap[id]) {
    this.cacheMap[id] = ...
  }

  return this.cacheMap[id];
}
cacheMap = {}

getById(id: number) {
  if (!this.cacheMap[id]) {
    this.cacheMap[id] = ...
  }

  return this.cacheMap[id];
}