属性 'do' 在类型 'Subscription' 上不存在

Property 'do' does not exist on type 'Subscription'

我对.subscribe函数与.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 调用之后捕获错误和 运行 一个 "always" 函数,如 _callApi.[=21 的第二个版本所示=]

_callApi 的第一个版本似乎 return 一个 Observable 而第二个 return 是一个 Subscription 对象。并且 Subscription 不会公开 do,正如错误消息所述。

您可能想要尝试的是使用 do 的版本,除了 next 回调之外,它还接受 errorcomplete 回调:

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

值得一提的是 do 无法转换源流,它 return 的可观察对象包含与调用它的可观察对象相同的值。这就是为什么我们需要行 .map(response => this._transformSubscriberInfo(response)).

此外,complete 回调不应与 "always" 函数混淆:只有当源可观察对象完成时才会调用它,当可观察对象产生错误或取消订阅时不会调用它。