Search code examples
angularxmlhttprequesthttpclientabort

Angular: abort POST request


The XMLHttpRequest.abort() aborts the request that was already sent. How could I achieve this in Angular, preferably with HttpClient?

Use case: The application is uploading files. I want the user to be able to cancel the request that is in progress.


Solution

  • Service:
    upload() {
      return this.httpClient.post(); // Some url etc.
    }
    
    Component:
      uploadFileSubscription: Subscription;
      uploadFile() {// executed by eg. click
      this.uploadFileSubscription = this.service.upload().subscribe();
    }
    

    Then whenever you want to cancel that upload request just execute this.uploadFileSubscription .unsubscribe();