Angular 中使用 rxjs 的映射结果

Mapping result with rxjs in Angular

我需要一些关于 Angular 中 rxjs 的帮助。

我有一个 API returns 我的后端数据的分页列表。结果的内容属性中有数据。内容的每个条目都没有 expanded 属性。当我在前端为模型定义接口时,我添加了该字段,但现在我需要以某种方式对其进行初始化。此代码与 for 循环一起使用,但我知道它可以通过 rxjs 中的管道和映射以某种方式完成。

冷你建议我该怎么做?

this.service.getData(page, size, id)
    .pipe(
      catchError(() => of([])),
      finalize(() => this.loadingSubject.next(false))
    )
    .subscribe((result: DataPage) => {
      this.dataSubject.next(result.content);
      for(let entry of this.dataSubject.value) {
        entry.expanded = false;
      
      this.totalElementsSubject.next(result.totalElements);
      this.loadingSubject.next(false);
    });

您可以使用 map 来自 rxjs:

this.service.getData(page, size, id)
  .pipe(
    catchError(() => of([])),
    map((result) => {
      return result.content.map((data) => {
        // We use the object coming from the backend as-is and add an `expanded: false` property.
        return {...data, expanded: false};
      });
    }),
    finalize(() => this.loadingSubject.next(false)),
  )
  .subscribe((data) => {
    this.dataSubject.next(data);
    this.totalElementsSubject.next(data.length);
    this.loadingSubject.next(false);
  });