gpt4 book ai didi

javascript - switchMap : Multiple (2) requests getting triggered

转载 作者:太空狗 更新时间:2023-10-29 17:46:59 26 4
gpt4 key购买 nike

我正在使用 Angular 2 RC-4。每当输入框发生变化时,我都会尝试发出网络请求。但是请求被调用了两次。

我的代码如下:

component.ts

this.term = new Control();

this.suggestions = this.term.valueChanges
// .debounceTime(1000)
// check if the search term's length is >= 1
.filter(term => term && term.length)

// switchMap only subscribes to one observable at a time so if a new key is
// pressed before the response of previous request has been recieved, it
// automatically un-subscribes from the previous observable thus cancelling the previous
// request.
.switchMap(term => this._suggestionsService.getSuggestions(term, uuid))

component.html

<ul [hidden]='!(suggestions | async)?.length'>
<li *ngFor='let suggestion of suggestions | async'>{{suggestion.name}}</li>
</ul>

suggestion.service.ts

getSuggestions(term){
return this.http.get('some-url')
.map((res: Response) => res.json());
}

这使得网络请求2次。但是如果我稍微更改组件中的代码并手动订阅而不是使用异步管道,则网络请求只会发出一次。

component.ts

this.term.valueChanges
.filter(term => term && term.length)
.switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
.subscribe(value => this.suggestions = value);

component.html

<ul [hidden]='!suggestions.length'>
<li *ngFor='let suggestion of suggestions'>{{suggestion.name}}</li>
</ul>

两者的结果都很好。我只关心网络请求的数量。我想我缺少一些关于可观察对象的概念。

最佳答案

问题是模板中有 2 个 async 导致 observable 被多次订阅,因此发出了 2 次请求。

使用 share 就可以了:

this.suggestions = this.term.valueChanges
.filter(term => term && term.length)
.switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
.share();

关于javascript - switchMap : Multiple (2) requests getting triggered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38754499/

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