首页 > 解决方案 > forkJoin 返回错误您在预期流的位置提供了“未定义”

问题描述

之前,我问过一个关于用等待子请求返回嵌套 httprequest 的问题。

https://stackoverflow.com/questions/69308614/angular-map-wait-observable-to-complete[Angular地图等待 Observable 完成] 1

我对其进行了一些更改,但它会引发错误

错误:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。

这是我的更新代码

      test2(): Observable<Student[]> {
    return this.test1().pipe(
      mergeMap((result) => {
        if (!result) {
          return of(result);
        }
        return forkJoin(
          result.map((rr) => {
            if (rr.age === 1) {
              rr.age = rr.age * 10;
              return of(rr);
            } else {
              this.client
                .get('https://api.coindesk.com/v1/bpi/currentprice.json')
                .pipe(
                  map((res) => {
                    console.log(res);
                    rr.age = rr.age * 10000;
                    return rr;
                  })
                );
            }
          })
        ).pipe(
          map((paths) => {
            console.log('w');
            console.log(paths);
            return paths;
            // return result.map((e, index) => ({
            //   age: paths[index],
            // }));
          })
        );
      })
    );
  }

标签: angularrxjsobservable

解决方案


您的代码中的问题是您在.map. 如果您在函数中使用条件.map,则需要添加return,因为错误指出流是预期的而不是未定义的。为了让你提供一个 observable,你需要在你的if-else条件下返回你的 observable。

return在下面的代码中,我在您of()和您的http通话中添加了关键字。我还创建了一个包含我的解决方案的stackblitz供您检查。

test2(): Observable < Student[] > {
  return this.test1().pipe(
    mergeMap((result) => {
      if (!result) {
        return of(result);
      }
      return forkJoin(
        result.map((rr) => {
          if (rr.age === 1) {
            rr.age = rr.age * 10;
            return of(rr);
          } else {
            return this.client
              .get('https://api.coindesk.com/v1/bpi/currentprice.json')
              .pipe(
                map((res) => {
                  console.log(res);
                  rr.age = rr.age * 10000;
                  return rr;
                })
              );
          }
        })
      ).pipe(
        map((paths) => {
          console.log('w');
          console.log(paths);
          return paths;
        })
      );
    })
  );
}

推荐阅读