2017-07-25 100 views
1

我對如何將.subscribe函數與.do函數結合使用產生誤解?「訂閱」類型中不存在屬性'do'

這是我觀察到的序列:

lookupSubscriber = (text$: Observable<string>) => 

    text$.debounceTime(300) 
    .distinctUntilChanged() 
    .do(() => this.searching = true) 
    .switchMap(term => { 
     var data = this._callApi(this.lookupSubscriberAPI, term) 
      .do(() => { 
       this.searchFailed = false; 
       this.searching = false; 
      }) 
      .catch(() => { 
       this.searchFailed = true; 
       this.searching = false; 
       return Observable.of([]); 
      }) 
     return data; 
    }) 
    .do(() => this.searching = false); 

如果我_callApi功能如下所示,它的工作原理:

_callApi(url: string, term: string) { 
    if (term === '') { 
    return of.call([]); 
    } 

    return map.call(this.dataService.get(url + term), response => { 
    var data = this._transformSubscriberInfo(response); 
    return data; 
    }) 

}

然而,當我嘗試用重寫一遍subscribe功能如下:

_callApi = (url: string, term: string) => { 

    return this.dataService.get(url + term) 
     .subscribe(
      response => { this._transformSubscriberInfo(response) }, 
      error => error.text(), 
      () => { 
       if (Logging.isEnabled.light) { 
       console.log('%c API Call Complete', Logging.normal.orange); 
       } 
     )) 
} 

...然後將數據調用成功,但我收到錯誤:Property 'do' does not exist on type 'Subscription'.

基本上我試圖抓住錯誤和運行API調用後的「永遠」功能,如圖中的_callApi第二個版本。

回答

4

_callApi的第一個版本似乎返回Observable,而第二個返回Subscription對象。並且Subscription不會公開do,正如錯誤消息所述。

你可能想嘗試什麼是使用一個版本的do接受除errorcomplete回調到next回調:

return this.dataService.get(url + term) 
    .map(response => this._transformSubscriberInfo(response)) 
    .do(
     response => { /* log response */ }, 
     error => { /* log error */ }, 
     () => { /* log completion */ } 
    ); 

它值得一提的是,do不能夠將源數據流的,它返回的observable包含與它被調用的可觀察值相同的值。這就是爲什麼我們需要行.map(response => this._transformSubscriberInfo(response))

complete回調不應該被混淆爲一個「always」函數:只有當源observable完成時它才被調用,並且當observable產生錯誤或取消訂閱時它不會被調用。

相關問題