Angular 9 取消 HTTP 请求 [英] Angular 9 cancel HTTP request

查看:47
本文介绍了Angular 9 取消 HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角 9

我想实现在用户单击按钮时取消 api 请求的功能.我正在使用订阅"所以我想取消订阅()"会工作得很好,但不像我预期的那样.

I want to implement function to cancel api request when user click a button. I'm using "subscribe" so I thought "unsubscribe()" would work well, but not as I had expected.

这是一个 stackblitz 示例代码,它调用/取消 api 请求,并且响应将显示在控制台中.

this is a stackblitz sample code, which call/cancel api request, and response would be shown in console.

https://stackblitz.com/edit/angular-cancel-pending-http-requests-yavvkb

在这段代码中,如下所示,我调用了unsubscribe()";取消被叫请求.实际上在调用unsubscribe()"之后,很快就到达了add().但不久之后,它收到了实际的 API 响应.

In this code, as below, I called "unsubscribe()" to cancel called request. Actually after calling "unsubscribe()", soon it reached to add(). but soon after, it received actual API response.

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]}.

search clicked.
cancel clicked.
complete.
unsubscribed.
{status: true, statusMessage: "Items fetched successfully", data: Array[10]}.

取消后,我不想收到回复,因为这是取消"的目的.但我不知道该怎么做.

After cancellation, I don't want to receive response because it's the purpose of "cancel". But I couldn't figure out how to do.

提前感谢您的帮助.

推荐答案

您可以将 takeUntil()Subject

我已经修改了你的 stackblitz 来使用这个:https://stackblitz.com/edit/angular-cancel-pending-http-requests-1g36pv?file=src/app/search/search.service.ts

I've modified your stackblitz to use this: https://stackblitz.com/edit/angular-cancel-pending-http-requests-1g36pv?file=src/app/search/search.service.ts

这篇关于Angular 9 取消 HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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