微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何订阅包含 Promise 的 Observables 链

如何解决如何订阅包含 Promise 的 Observables 链

我有一个嵌套的 Observable 情况,经过一些研究我发现最好使用 RxJS switchMap

就我而言,第一个 observable 包含 Promise,因此我必须等待第一个订阅结果,然后才能将其传递给第二个 observable。现在第二个 Observable 没有被订阅,而是返回一个 Observable 而不是订阅它的结果。

firstObservable(x) {
  return this.productService.getProduct(x).pipe(
    map(async result => {
       this.productObject = {...result};
       let timeVariable = await 
       this.distanceMatrixService.getTime(this.productObject,this.currentLocation);
       return this.productObject;
    })
}

async secondobservable(passedProductObject) {    
  const productObject = await passedProductObject;
  return this.productService.getProductsByShop(productObject.store_id).pipe(
    map(result => {
      ////STUFF that depends on the timeVariable 
    }));
} 

chainingObservables(x) {
  return this.firstObservable(x).pipe(
  switchMap(async x => this.secondobservable(x)));
}

this.chainingObservables(this.passedData).subscribe(res => {
 console.log("result",res);
})

result Observable {_isScalar: false,source: Observable,operator: MapOperator}

任何建议将不胜感激。

解决方法

您可以使用像这样的 switchMap 运算符在管道链中执行此操作。

你不应该使用 observables 的异步

假设 this.distanceMatrixService.getTime 返回一个有效的 promise。

    observable(x) {
        return this.productService.getProduct(x).pipe(
            tap(result => {
                this.productObject = {...result};
            }),switchMap(() => {
                return from(this.distanceMatrixService.getTime(this.productObject,this.currentLocation))
                    .pipe(map((time) => [time,this.productObject]));
            }),switchMap(([time,passedProductObject]) => {
                return this.productService.getProductsByShop(passedProductObject.store_id).pipe(
                    map(result => {
                        ////STUFF that depends on the timeVariable
                        return time;
                    }));
            }));
    }

    subMethod(x) {
        this.observable(this.passedData).subscribe(res => {
            console.log('result',res);
        });
    }
,

您可以使用 RxJS from 函数将承诺转换为可观察的。之后,使用 switchMap 的几个 map 应该足以满足您的要求。

试试下面的方法

this.productService.getProduct(x).pipe(
  map(result => ({...result})),switchMap(productObject => 
    from(this.distanceMatrixService.getTime(productObject,this.currentLocation)).pipe(
      map(timeVariable => ({
        productObject: productObject,timeVariable: timeVariable
      }))
    )
  ),switchMap(({productObject,timeVariable}) =>
    this.productService.getProductsByShop(productObject.store_id).pipe(
      map(result => {
        // stuff that depends on `timeVariable`
      })
    )
  )
).subscribe(
  res => {
    console.log("result",res);
  },error => {
    // handle error
  }
);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。