【发布时间】:2020-08-11 18:19:15
【问题描述】:
角度 9
我想实现在用户单击按钮时取消 api 请求的功能。 我正在使用“订阅”,所以我认为“取消订阅()”会很好用,但不像我预期的那样。
这是一个stackblitz示例代码,它调用/取消api请求,响应将显示在控制台中。
https://stackblitz.com/edit/angular-cancel-pending-http-requests-yavvkb
在这段代码中,如下所示,我调用了“unsubscribe()”来取消调用的请求。 实际上在调用“unsubscribe()”之后,很快就到了add()。但不久之后,它收到了实际的 API 响应。
export class SearchService {
private foo: any = null;
constructor(private apiService: ApiService) { }
public getItemList() {
this.fetchData();
}
public cancel() {
if(this.foo != null) {
this.foo.unsubscribe();
console.log('unsubscribed');
}
}
private fetchData(){
const endPoint: string = 'https://www.mocky.io/v2/5c245ec630000072007a5f77?mocky-delay=2000ms';
this.foo = this.apiService.getData(endPoint).subscribe((resp)=>{
console.log(resp);
},(err)=>{
console.log(err);
}).add(() => {
this.foo = null;
console.log('complete');
});
}
}
输出是
点击了搜索。
取消点击。
完成。
已退订。
{status: true, statusMessage: "Items fetched successfully", data: Array[10]}.
取消后,我不想收到回复,因为这是“取消”的目的。 但我不知道该怎么做。
提前感谢您的帮助。
【问题讨论】:
标签: angular