如何使用 switchMap 取消挂起的 http 请求并只接受最后一次订阅? [英] how to use switchMap to cancel pending http requests and taking the last subscribe only?
问题描述
我尝试使用 subscription.unsubsribe 取消挂起的 http 请求,如下所示:
i tried canceling pending http request using subscription.unsubsribe like this:
getAgentList(pageNumber: number, filter: string): any {
let requestUrl: string = 'api/service/agents_search?ACCT='
+this.accountId;
if ( this.subscription ) {
this.subscription.unsubscribe();
}
this.subscription = this.backEndCommService.getData(requestUrl)
.subscribe(
(res: any) => {
let serverResponse: ServerResponse = new
ServerResponse(this.accountId, pageNumber, res.search_results,
res.resultRows, res.pageSize, res.resultPages)
this._agentListData.next(serverResponse);
},
(err: HttpErrorResponse) => {
let errorMessage: string;
if (err instanceof TypeError) {
errorMessage = 'Script error: ' + err.message;
}
console.log(errorMessage);
});
}
我想知道如何将 switchMap 应用到此代码以终止对 URL 的待处理请求(例如,当第一次搜索需要很长时间并输入第二次时自动完成搜索输入,我想关闭第一个.)谢谢
I wonder how can I apply switchMap to this code in order to kill pending requests to the URL ( for example autocompletion search input when first search taking to much time and a second one entered and I want to dismiss the first one.) thanks
推荐答案
基本示例:
export class MyComponent{
private $filter: Subject<string> = new Subject<String>();
constructor(){
this.$filter
.switchMap(filter => this.backEndCommService.getData(filter + this.baseUrl)
.subscribe(res => {//do something})
}
getAgentList(filterValue: string){
this.$filter.next(filterValue);
}
}
要使用 switchmap 取消先前的请求,我们需要一个热可观察对象来输出我们的过滤器值.我们为此使用了一个主题.每次我们从某个地方获得一个新值?我们把它推到主题.
To use switchmap to cancel previous request we need a hot observable which outputs our filter value. We use a subject for that. Everytime we get a new value from somewhere? we push it to the subject.
这篇关于如何使用 switchMap 取消挂起的 http 请求并只接受最后一次订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!