首页 > 解决方案 > 转换为 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);
  }
}

标签: angularrxjs

解决方案


未经测试,但应该可以工作。

请注意,订阅者将在每次调用 后发出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))
        );
    }
}

推荐阅读