温馨提示:本文翻译自stackoverflow.com,查看原文请点击:angular - How to perform one async action after another without embedded subscriptions
angular observable rxjs subscription

angular - 如何在没有嵌入式订阅的情况下执行一个异步动作

发布于 2020-04-14 17:49:00

我想使用rxjs一个接一个地执行异步操作。我知道在订阅中嵌入订阅不是一个好习惯,还有其他一些rxjs运算符(flatMap \ mergeMap,do等使用pipe)。

我需要获取组件queryparams,设置全局变量(globalVar),然后继续下一个异步操作(this..doSomething())。这是我使用嵌入式订阅的代码:* doSomething返回一个可观察到的

this.route.paramMap.subscribe(params => 
    { 
      globalVar = + params['userId']; 
      this.<someService>.doSomething().subscribe(result => 
      {
        this.func1();
      });
    }

查看更多

提问者
Guy E
被浏览
42
Християн Христов 2020-02-04 00:26

对于要链接多个可观察对象的情况,理想的解决方案是switchMap运算符。

this.route.paramMap
    .pipe(
      switchMap(params) => {
      globalVar = + params['userId']; 
      return this.<someService>.doSomething()
    })
    .subscribe(result=> {this.func1();})

这事情switchMap需要做的是从获得PARAMS后,this.route它会返回一个新的观察到的,可以为其后者订阅。switchMap在这种情况下使用的好处是,如果处理中this.route.paramMapwhile 内有更改this.<someService>.doSomething(),rxjs将终止正在处理的请求并开始新的请求,这样,结果内部的日期subscribe将始终与当前日期相关。的价值paramMap