Angular 9 cancel HTTP request

Viewed 4858

Angular 9

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.

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

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

output was

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.

Thank you for your kind help, in advance.

1 Answers
Related