【问题标题】:RxJS : How to get output from Outer & Inner Observable in AngularRxJS:如何在 Angular 中从外部和内部 Observable 获取输出
【发布时间】:2019-09-09 15:17:07
【问题描述】:

我已经订阅了查询参数,我可以从中获取商品代码。我们如何从 getItemDetails 和 getSecuredData 一起获取数据

而不是使用多个 subscribe()。我使用了mergeMap 运算符

this.route.queryParams.pipe(mergeMap( params => {
      const itemCode = params.ItemCode
      return this.dataService.getItemDetails(itemCode)
             .pipe(mergeMap((ItemData) => {
               console.log(ItemData)   // I can see the Item Data
               return this.dataService.getSecureData(itemCode)
             }))
    })).subscribe( response => {
        console.log(response)    // It's blank (Ideally I should get the Item 
                                    Data & SecuredData)
    })

有什么我经过的吗?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    您需要使用switchMapForkJoin 的组合。

    您必须从 params.ItemCode 切换到 fork 连接,以便从这两个服务中获取最新信息,因为它们都依赖于 ItemCode。每次发出新的ItemCode 时,都会并行获取两个服务,但您只需要每个服务的第一个值。

       const itemCode$ = this.route.queryParams.pipe(map(params => params.ItemCode));
       const itemDetails$ = (itemCode) => this.dataService.getItemDetails(itemCode).pipe(first());
       const secureData$ = (itemCode) => this.dataService.getSecureData(itemCode).pipe(first());
    
       const value$ = itemCode$.pipe(
          switchMap(itemCode => forkJoin({
              itemCode: of(itemCode),
              itemDetails: itemDetails$(itemCode),
              secureData: secureData$(itemCode)
          }))
      );
    
      value$.subscribe(value => console.log(value)); // prints {itemCode: xxx, itemDetails: xxx, secureData: xxx}
    

    【讨论】:

    • 好的@Reactgular !从 params.itemCode 切换到 forkjoin 到底是什么以及我们为什么使用 first() ?
    【解决方案2】:

    您可以像这样将外部可观察数据与内部可观察数据映射,以获得可观察数据的最终输出,该可观察数据将具有外部可观察数据和内部可观察数据:

    this.route.queryParams
            .pipe(
    
              //AS PER YOUR NEED YOU CAN USE SWITCHMAP as well
              mergeMap(params => {
                        const itemCode = params.ItemCode
                        return this.dataService.getItemDetails(itemCode)                               
                      }),
              //AS PER YOUR NEED YOU CAN USE SWITCHMAP as well
              mergeMap(itemDetails => {
                return this.dataService.getSecureData(itemCode)
                           .pipe(
                             map(secureData => {
                               return {itemDetails, secureData};
                             })
                           )
              })
            )
        .subscribe( response => {
            //response will have an object which will have two properties 
            //{itemDetails, secureData}
            console.log(response) 
        });
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-25
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2012-11-01
      • 2022-12-18
      相关资源
      最近更新 更多