gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:32:48 25 4
gpt4 key购买 nike

我对如何结合使用 .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 调用后捕获错误并运行“始终”函数,如 _callApi 的第二个版本所示。

最佳答案

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

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

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

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

此外,complete 回调不应与“始终”函数混淆:它仅在源可观察对象完成时被调用,而当可观察对象产生错误或取消订阅时不会被调用。

关于javascript - 类型 'do' 上不存在属性 'Subscription',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45314976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com