angular - 转换为 rxjs 方法
问题描述
我想将以下 2 种方法转换为 rxjs 方法。我怎样才能做到这一点。第二种方法取决于第一种方法的结果。
export class EntityStorage {
private entitiesStore: Map<string, any[]> = new Map<string, any[]>();
constructor(private apiService: ApiService) {}
loadAllEntity(key: string, httpParams: HttpParams): void {
this.apiService.getEntities(key, httpParams).subscribe(
(entities) => {
this.entitiesStore.set(key, entities);
},
(error) => {
console.error(error);
},
() => {}
);
}
getStoreWithKey(key: string): any[] {
return this.entitiesStore.get(key);
}
}
解决方案
未经测试,但应该可以工作。
请注意,订阅者将在每次调用 后发出loadAllEntity
,因此请考虑使用take(1)
忽略进一步的更新。
export class EntityStorage {
private $entitiesStore = new ReplaySubject<Map<string, any[]>>();
private entitiesStore: Map<string, any[]> = new Map<string, any[]>();
constructor(private apiService: ApiService) {}
loadAllEntity(key: string, httpParams: HttpParams): void {
this.apiService.getEntities(key, httpParams).subscribe(
(entities) => {
this.entitiesStore.set(key, entities);
this.$entitiesStore.next(this.entitiesStore);
},
(error) => {
console.error(error);
},
() => {}
);
}
getStoreWithKey(key: string): Observable<any[]> {
return this.$entitiesStore.pipe(
map((entitiesStore) => entitiesStore.get(key))
);
}
}
推荐阅读
- c# - 使用 MediaPlayerElement 播放 RTSP
- html - 如何使用 CSS 删除特定边框
- python - 我无法通过 python 请求绕过 cloudflare
- python - 用 numdifftools 计算粗麻布矩阵
- r - 在 dplyr 中改变多个 cumsum
- cryptojs - 错误[E0463]: 找不到 `core` 的 crate | = 注意:可能未安装“x86_64-fortanix-unknown-sgx”目标
- python - Python:以相反的顺序打印输入(条件:只有单词(至少4个单词))
- python - 我什么时候应该在 tkInter 中为 python 使用 root.update()
- r - 使用 nls 处理 Sapply 循环中的错误 - 循环在第一个错误处停止并且不输出任何数据
- jquery - 克隆表的选择器?表2excel