2017-09-20 96 views
1

下午好!返回從嵌套回調函數內部觀察

我目前正在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

回答

3

你在找什麼是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';'。非常感謝你! –