【问题标题】:forkJoin return error You provided 'undefined' where a stream was expectedforkJoin 返回错误您在预期流的位置提供了“未定义”
【发布时间】:2021-11-29 22:46:21
【问题描述】:

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

https://stackoverflow.com/questions/69308614/angular-map-wait-observable-to-complete[Angularmap 等待 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],
            // }));
          })
        );
      })
    );
  }

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

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

    在下面的代码中,我在您的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;
            })
          );
        })
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2021-05-21
      • 2020-03-26
      • 1970-01-01
      • 2022-01-17
      • 2020-06-16
      • 2018-05-31
      • 2021-09-10
      • 2018-11-08
      相关资源
      最近更新 更多