如何使用switchMap取消待处理的http请求并仅接受最后一个订阅? [英] how to use switchMap to cancel pending http requests and taking the last subscribe only?

查看:349
本文介绍了如何使用switchMap取消待处理的http请求并仅接受最后一个订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆