【问题标题】:Property 'do' does not exist on type 'Subscription'“订阅”类型上不存在属性“do”
【发布时间】:2017-07-25 23:22:57
【问题描述】:

我对如何将.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 的第二个版本所示。

【问题讨论】:

    标签: javascript angular rxjs observable subscribe


    【解决方案1】:

    _callApi 的第一个版本似乎返回一个Observable,而第二个版本返回一个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 无法转换源流,它返回的 observable 包含与调用它的 observable 相同的值。这就是我们需要.map(response =&gt; this._transformSubscriberInfo(response))这一行的原因。

    此外,complete 回调不应与“always”函数混淆:它仅在源 observable 完成时被调用,并且在 observable 产生错误或被取消订阅时不会被调用。

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 2018-12-02
      • 1970-01-01
      • 2017-10-13
      • 2018-03-25
      相关资源
      最近更新 更多