如何使用switchMap取消待处理的http请求并仅接受最后一个订阅?

Sha*_*aim 1 httprequest observable rxjs angular switchmap

我试图使用subscription.unsubsribe取消待处理的http请求,如下所示:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何将switchMap应用于此代码,以便杀死对URL的挂起请求(例如,当第一次搜索花费大量时间,而第二次输入时要输入第一个,而我想取消第一个,则自动完成搜索输入)。

Rob*_*hof 5

基本示例:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

要使用switchmap取消先前的请求,我们需要一个可观察到的热点,它输出我们的过滤器值。我们为此使用一个主题。每当我们从某个地方获得新的价值时?我们将其推向主题。