作者:我要做一颗树树树 | 来源:互联网 | 2022-12-25 12:38
我试图使用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);
});
}
我想知道如何将switchMap应用于此代码,以便杀死对URL的挂起请求(例如,当第一次搜索花费大量时间,而第二次输入时要输入第一个,而我想取消第一个,则自动完成搜索输入)。
1> Robin Dijkho..:
基本示例:
export class MyComponent{
private $filter: Subject = new Subject();
constructor(){
this.$filter
.switchMap(filter => this.backEndCommService.getData(filter + this.baseUrl)
.subscribe(res => {//do something})
}
getAgentList(filterValue: string){
this.$filter.next(filterValue);
}
}
要使用switchmap取消先前的请求,我们需要一个可观察到的热点,它输出我们的过滤器值。我们为此使用一个主题。每当我们从某个地方获得新的价值时?我们将其推向主题。