RxJs / Angular:通过地图循环内的订阅获取其他数据

我对angular和rxjs很陌生,但我解决不了。 我知道我的代码是错误的,但是我不知道如何正确编写它。

我正在通过HTTP请求获取JSON,JSON包含数组中的数据。 之后,我想遍历JSON数据中的数组并获取另一个HTTP端点的其他数据。

我查看了flatMap,switchMap等,在我的案例中我无法确定要组合这些命令。

感谢大伙们!

到目前为止,我的代码:

  checkMatches() {
    this.http.get<{
      message: string,
      result: any}>
    (BACKEND_URL + 'matches')
        .pipe(map((matchData) => {
          return {matches: matchData.result.map(match => {
            this.userService.getUserData(match.matchedUser).subscribe(userData => {
              console.log(userData);
            }
              );
            return {
              id: match._id,
              matchedUser: match.matchedUser,
              firstMatch: match.firstMatch,
              name: userData.userName,
              img: userData.userImg,
              status: match.status,
            };
          })};
        }))
        .subscribe(transformedMatchData => {
        console.log(transformedMatchData);
        });
  }
评论
  • lvero
    lvero 回复

    It looks like for every reponse of matches, you need to query APIS, you can use swicthMap() along with forkJoin here:

    Using switchMap would merge (BACKEND_URL + 'matches') say Parent observable url observable along with next observables we create with its result, and also, it cancels new requests of if parent observable emits again.

    Using forkJoin would make you wait for all the child observables to complete before emitting data.

    checkMatches() {
        this.http.get<{
        message: string,
        result: any}>
        (BACKEND_URL + 'matches')
            .pipe(switchMap((matchData) => {
                return forkJoin(
                    ...matchData.result.map(match => {
                        return this.userService.getUserData(match.matchedUser).pipe(
                            map((userData) => {
                                return {
                                    id: match._id,
                                    matchedUser: match.matchedUser,
                                    firstMatch: match.firstMatch,
                                    name: userData.userName,
                                    img: userData.userImg,
                                    status: match.status,
                                };
                            })
                        )
                    })
                )
            }))
            .subscribe(transformedMatchData => {
                console.log(transformedMatchData);
            });
    }