返回从嵌套回调函数内部观察

返回从嵌套回调函数内部观察

问题描述:

下午好!返回从嵌套回调函数内部观察

我目前正在Angular2/4上开发一个Web应用程序,并且我有一个Observable问题。目标是在一个组件内部调用一个函数,当该函数完成时,我想要执行一些代码。所以,在“myComp.component.ts”文件的代码是:

this.myService.myFunc1().subscribe(() => { 
    // this code has to be executed after myFunc1() finishes. 
}); 

的问题是“myService.service.ts” 的“myFunc1()”功能文件中。该功能的结构是下面的:

  1. 定义函数,该函数返回一个Observable<Status>,其中状态对象就是{ status: 'ok' }
  2. 从另一个服务调用函数“myFunc2()”,该服务返回Observable并执行一些工作。
  3. 调用函数“myFunc3()”从其他服务,这将返回一个可观察并具有后“myfunc2所()”饰面被执行。
  4. 调用函数“myFunc4()”从其他服务,这将返回一个可观察并具有后“myFunc3()”饰面被执行。
  5. { status: 'ok' }返回到“myComp.component.ts”,以便执行subscribe()中的其他代码。

所以我需要的是(3)一些函数的嵌套调用,它们中的每一个都要在前一个函数之后执行。最简单的方法如下:

myFunc1(): Observable<Status> { 
    // some code and then call of myFunc2() 
    this.myService2.myFunc2().subscribe(data => { 
     // do some staff here and then call of myFunc3() 
     this.myService3.myFunc3().subscribe(data2 => { 
      // do some other staff and then call of myFunc4() 
      this.myService4.myFunc4().subscribe(data3 => { 
      // do staff and then return program flow into the Component 
      return Observable.of<Status>({status: 'ok'}); 
      }); 
     }); 
    }); 
} 

但当然return Observable.of<Status>({status: 'ok'});不起作用。我一直在寻找互联网和其他#1问题的一个解决方案,我发现像使用flatMap()mergeMap()switchMap()的建议等,我觉得这些解决方案不能使用我的情况,因为每个函数都必须在另一个之后执行。

我该怎么办?我在这里想念什么?提前感谢您的帮助和时间!

+1

你可以尝试使用[combineLatest]您多次观测相结合(http://reactivex.io/documentation/operators/combinelatest.html)或[拉链](http://reactivex.io/documentation/运营商/ zip.html)取决于您的要求! – JayDeeEss

+0

首先你没有在你的函数中返回任何东西,所以它不会编译。其次,即使你在这种情况下返回,“订阅”将返回一个订阅,而不是一个可观察的。使用switchMap是正确的链接方式。确保您返回,然后在您调用它时订阅该方法。 – Eeks33

你在找什么是switchMap或mergeMap。开关地图更好,它会取消以前的请求,如果新的出来。

myFunc1(): Observable<Status> { 
    // some code and then call of myFunc2() 
    return this.myService2.myFunc2() 
     .switchMap(data => { 
     // do some staff here and then call of myFunc3() 
     return this.myService3.myFunc3() 
     }).switchMap(data2 => { 
      // do some other staff and then call of myFunc4() 
      return this.myService4.myFunc4() 
     }).switchMap(data3 => { 
      // do staff and then return program flow into the Component 
      return Observable.of<Status>({status: 'ok'}); 
      }); 
     }); 
    }); 
} 
+0

它的工作原理。它还需要'import'rxjs/add/operator/switchMap';'。非常感谢你! –