forkJoin return 错误您提供了 'undefined' 预期流的位置

forkJoin return error You provided 'undefined' where a stream was expected

之前,我问过一个关于 return 带有等待子请求的嵌套 httprequest 的问题。

map wait Observable to complete]

我对它做了一些修改,但它抛出错误

错误:您在需要流的地方提供了 'undefined'。您可以提供 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],
            // }));
          })
        );
      })
    );
  }

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

在下面的代码中,我在您的 of()http 调用中添加了关键字 return。我还创建了一个 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;
        })
      );
    })
  );
}