【问题标题】:rxjs expand operator with switchMaprxjs 使用 switchMap 扩展运算符
【发布时间】:2022-01-03 17:49:46
【问题描述】:

我有一个学生列表,对于每个学生,我都必须访问该地址。我将在分页中获取学生列表。所以我使用“扩展”运算符来获取所有学生。但我无法获得每个学生的地址。 学生名单

{
  students: [
    {
      id: 1,
      name: 'ABC'
    },
    {
      id: 2,
      name: 'XYZ'
    }
  ],
 nextPageToken: 'Aqw12'
}

现在我必须使用学生的 id 来获取地址。 这是我使用 rxjs 扩展运算符获取学生列表的示例代码。

const connection = this.searchStudent(nextPageToken).pipe(
    expand((students: StudentsDto) => {
        if (students.nextPageToken){
            nextPageToken = students.nextPageToken;
            return this.searchStudent(nextPageToken);
        }else{
            return new Observable as Observable<StudentsDto>;
        }
    })
);

const subscription = connection.subscribe({
    next(response: StudentsDto) {
        response.students.forEach(async (student: StudentDto) => {
            console.log(student);
        });
    },
    error(e) {
        console.log(e)
    },
    complete() {
        subscription.unsubscribe();
    },
});

现在我无法获取,我应该申请哪个运营商来获取地址。 对于地址,我在返回 Observables 的 this.getAddress(studentId) 函数中实现了 API。

请帮忙, 谢谢。

【问题讨论】:

  • 假设您的连接 observable 工作正常,那么您可以使用一个 mergeMap,它接收 StudentDto 数组并从中获取各个地址
  • @Pankaj 是的,可观察到的连接工作正常。我应该在扩展运算符中使用 mergeMap 吗?我很困惑。

标签: axios rxjs nestjs


【解决方案1】:
const connection = this.searchStudent(nextPageToken).pipe(
    expand((response: StudentsDto) => {
        if (response.nextPageToken){
            nextPageToken = response.nextPageToken;
            return this.searchStudent(nextPageToken);
        }else{
            return new Observable as Observable<StudentsDto>;
        }
    }),
    mergeMap((response: StudentsDto) => {
        return response.students.map(student => this.getAddress(student.id))
    }),
    mergeAll(),
);

const subscription = connection.subscribe({
    next(response: AddressDto) {
        // Perform/save operation on Address object
    },
    error(e) {
        console.log(e)
    },
    complete() {
        subscription.unsubscribe();
    },
});

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
相关资源
最近更新 更多