取消挂起的$http请求



我开始使用angular 6和Web API开发单页应用程序。我有一个搜索框,可以搜索有关键事件的数据。我看到首先加载旧响应的行为,然后加载下一个在慢速连接上看起来不太好的响应。如何在每次使用新字符或更少字符触发键时取消挂起的搜索请求。

要取消正在进行的请求,您可以取消订阅可观察量。更好的是,如果您使用switchMap运算符,它将为您执行此操作。

如果您使用可观察性来发出 http get 请求,您可以在发出新请求之前取消上一个 http 请求的订阅,即在您的情况下的每个 keyup 上。 在下面的示例中,假设 MyCustomSearchService 是一个具有返回 http 响应的方法getSearchResult(searchText)的服务,即return this.http.get(this.apiCallURL+searchText)

export class MySinglePageAppComponent{
private searchSubscription:any;//property that will store the search http subscription
private searchText:string;//search text binded to your text box
constructor(private myCustomSearchService: MyCustomSearchService) 
{}
//function called upon keyup
getSearchValue(){
//if already searched something then cancel its subscription.
if(this.searchSubscription){
this.searchSubscription.unsubscribe();
}
this.searchSubscription=this.myCustomSearchService.getSearchResult(this.searchText).subscribe((response)=>{
let resultJSON=JSON.parse(response.json())
//rest of the search hadler logic here
});
}
}

这样,以前的待处理请求将被取消。

您可以使用 KeyUp/KeyDown 事件来触发事件;在取消订阅的情况下,请求设置为可观察量。

键升/键下 https://angular.io/guide/user-input

退订:

let sub = this.http.get(url, {headers: reqHeaders})
.subscribe(
(res) => {
...
}
);
sub.unsubscribe();

最新更新