Angular Rxjs如何缓存给定参数的可观察结果?

Angular Rxjs如何缓存给定参数的可观察结果?,angular,typescript,rxjs,rxjs6,rxjs-observables,Angular,Typescript,Rxjs,Rxjs6,Rxjs Observables,在我的应用程序中,我使用rxjs,我有一个如下的方法: query<T extends TableRow>(queryString: string, silent = false): Observable<T[]> { return this.sqliteService.dbQuery<T>(queryString).pipe( tap(val => { if (this.configService.debugMode &

在我的应用程序中,我使用rxjs,我有一个如下的方法:

query<T extends TableRow>(queryString: string, silent = false): Observable<T[]> {
  return this.sqliteService.dbQuery<T>(queryString).pipe(
    tap(val => {
      if (this.configService.debugMode && !silent) {
        console.log(`\n${queryString}`);
        console.log(val);
      }
    })
  );
}
query(queryString:string,silent=false):可观察{
返回此.sqliteService.dbQuery(queryString).pipe(
点击(val=>{
if(this.configService.debugMode&&!静默){
log(`\n${queryString}`);
控制台日志(val);
}
})
);
}
我的
query
方法交替调用查询sqlite数据库的
dbQuery

另外,在我的应用程序中,
query
方法被多次调用。因此,每当
queryString
相同时,我都希望全局缓存结果

换句话说,我希望
query
方法在使用以前调用过的
queryString
参数调用时,通过返回以前缓存的值,避免再次调用
dbQuery


不确定这是否相关:我的
query
方法存在于Angular singleton服务中。

第一次通过,使用作为查询字符串的键将远程值保存到本地缓存属性

在后续请求中,返回相应键的现有属性

private cache={};
查询(queryString:string,silent=false):可观察{
if(this.cache.hasOwnProperty(queryString)){
返回(this.cache[queryString]);
}
返回此.sqliteService.dbQuery(queryString).pipe(
点击(val=>{
this.cache[queryString]=val;
if(this.configService.debugMode&&!静默){
log(`\n${queryString}`);
控制台日志(val);
}
})
);
}

我最终得到了以下解决方案:

private cache: Observable<string>[] = [];

getItem(id: number): Observable<string> {

  if (!this.cache[id]) {
    this.cache[id] = this.query<string>(
      `SELECT column FROM table WHERE id = ${id}`
    ).pipe(shareReplay());
  }

  return this.cache[id];
}
私有缓存:可观察[]=[];
getItem(id:number):可观察{
如果(!this.cache[id]){
this.cache[id]=this.query(
`从id=${id}的表中选择列`
).pipe(shareReplay());
}
返回此.cache[id];
}

谢谢@Kurt,不过我希望有一些内置的RXJ,它必须保留函数之外的值——无论是您自己的主体还是对象。函数中存储的任何状态或对函数中创建的可观察对象的引用都将在可观察对象返回时消失。此外,随着
缓存
对象的大小增加,我想知道它最终是否会更有效