2017-10-13 123 views
4

我需要做API調用來顯示某些事情的進度。長角度投票4

我創建了這個做每1.5秒

主要成分

private getProgress() { 
     this.progressService.getExportProgress(this.type, this.details.RequestID); 
    } 

Services.ts

public getExportProgress(type: string, requestId: string) { 
    Observable.interval(1500) 
     .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId)) 
     .map((data) => data.json().Data) 
     .subscribe(
     (data) => { 
      if (!data.InProgress) 
       //Stop doing this api call 
     }, 
     error => this.handleError(error)); 
} 

呼叫作品的服務,但它一直會。當進程完成時,我想停止執行API調用(if (!data.InProgress),但我堅持這一點。

如何在if (!data.InProgress)時正確取消訂閱此可觀察項?

感謝

回答

5

你可以使用takeWhile操作。

這裏是文檔: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-takeWhile

可發出,只要由源可觀察發射爲每個值 滿足給定的謂詞值,然後儘快完成,因爲這 謂詞是不滿意。

這是一個普通的例子: https://rxviz.com/v/yOE6Z5JA

Rx.Observable 
    .interval(100) 
    .takeWhile(x => x < 10) 
    .subscribe(x => { console.log(x); }); 

這裏是你的代碼的例子:

public getExportProgress(type: string, requestId: string) { 
    Observable.interval(1500) 
     .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId)) 
     .map((data) => data.json().Data) 
     .takeWhile((data) => data.InProgress) 
     .subscribe(
     (data) => { 
      ... 
     }, 
     error => this.handleError(error)); 
} 
1

我已經把服務調用的一個變量,和取消從該變量,當我做解決了這個。

這裏的結果:

public getExportProgress(type: string, requestId: string): any { 
    let progress = Observable.interval(1500) 
     .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId)) 
     .map((data) => data.json().Data) 
     .subscribe(
     (data) => {    
      if (!data.InProgress) { 
       this.toastyCommunicationService.addSuccesResponseToast("done"); 
       progress.unsubscribe(); 
      }    
     }, 
     error => this.handleError(error)); 
}