RxJS:如何从Angular中的“外部”和“内部”获取输出

时间:2019-09-09 15:17:07

标签: angular rxjs

我已经订阅了queryparams,从中我获得了商品代码。我们如何从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)
    })

我要传递什么东西吗?

2 个答案:

答案 0 :(得分:0)

您可以像这样将外部可观测数据与内部可观测数据进行映射,以获取可观测对象的最终输出,该输出将具有外部可观测数据以及内部可观测数据:

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) 
    });

希望有帮助。

答案 1 :(得分:0)

您需要结合使用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}