首页 > 解决方案 > RxJs 和 Angular,我需要从路由中读取两个参数,并且我想使用可管道操作符

问题描述

给定一个 Angular 路由,我需要依次从路由器中读取两个参数。实际上我的代码有嵌套订阅,但我不太喜欢它们

  this.route.parent.parent.params.subscribe(params => { 
      //read 'params'
      this.route.parent.parent.data.subscribe(anotherParams => {
         //read 'anotherParams' and do some thing with 'params'
       })
   })

我想使用 rxjs 运算符编写一次“订阅”,并在其中提供对两个参数的访问权限。

像这样的东西:

 this.route.parent.parent.params.pipe( //some operators )
 .subscribe ( params, anotherParams => {
    'params' and 'anotherParams" readable inside that
  })

标签: angularrxjsrxjs-pipeable-operators

解决方案


您可以使用mergeMapconcatMapswitchMap为您订阅另一个内部可观察对象。

下面是一个使用 switchMap 的示例:

this.route.parent.parent.params.pipe(
  switchMap(params => this.route.parent.parent.data.pipe(
    map(otherParams => ({params , otherParams }))
  ))
).subscribe(({params, otherParams}) => {
  // 'params' and 'anotherParams" readable inside that
});

推荐阅读