下午好!返回從嵌套回調函數內部觀察
我目前正在Angular2/4上開發一個Web應用程序,並且我有一個Observable問題。目標是在一個組件內部調用一個函數,當該函數完成時,我想要執行一些代碼。所以,在「myComp.component.ts」文件的代碼是:
this.myService.myFunc1().subscribe(() => {
// this code has to be executed after myFunc1() finishes.
});
的問題是「myService.service.ts」 的「myFunc1()」功能文件中。該功能的結構是下面的:
- 定義函數,該函數返回一個
Observable<Status>
,其中狀態對象就是{ status: 'ok' }
。 - 從另一個服務調用函數「myFunc2()」,該服務返回Observable並執行一些工作。
- 調用函數「myFunc3()」從其他服務,這將返回一個可觀察並具有後「myfunc2所()」飾面被執行。
- 調用函數「myFunc4()」從其他服務,這將返回一個可觀察並具有後「myFunc3()」飾面被執行。
- 將
{ 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()的建議等,我覺得這些解決方案不能使用我的情況,因爲每個函數都必須在另一個之後執行。
我該怎麼辦?我在這裏想念什麼?提前感謝您的幫助和時間!
你可以嘗試使用[combineLatest]您多次觀測相結合(http://reactivex.io/documentation/operators/combinelatest.html)或[拉鍊](http://reactivex.io/documentation/運營商/ zip.html)取決於您的要求! – JayDeeEss
首先你沒有在你的函數中返回任何東西,所以它不會編譯。其次,即使你在這種情況下返回,「訂閱」將返回一個訂閱,而不是一個可觀察的。使用switchMap是正確的鏈接方式。確保您返回,然後在您調用它時訂閱該方法。 –
Eeks33