how to cancel one of the pending http request from many angular 8

Viewed 668

I have an implementation for a file upload api using drag and drop multiple files. I am making a call within the for loop as below

uploadFile(file:any[]) {
    file.forEach((file, index)=>{
      const formData = new FormData();
      formData.append('report_file', file);
      this.fileService.uploadFile(this.configurations.uploadUrl, formData)
      .subscribe(fileResp=>{
        console.log('file', fileResp);
      }, error=>{
        console.log('error while uploading files', error);
      });
  });
}

This works while uploading. However, I have a requirement to be able to cancel one of the pending file if needed. so, how do I cancel a particular http request if user is opting to cancel that upload? for the bulk cancel I can do unsubscribe to my observable but in this case I need to make others still be uploading.

1 Answers

Here's an idea:

const files$ = from(files);

files$.pipe(
  mergeMap(
    file => this.fileService.uploadFile(/* ... */).pipe(
      takeUntil(fromEvent(getButtonThatCorrespondsToFile(crtFile), 'click').pipe(take(1)))
    )
  )
)

function getButtonThatCorrespondsToFile (): HTMLButtonElement { }
  • mergeMap - will allow you to start making a request for each file at the same time
  • takeUntil - attached to the request's observable of each file; makes sure that when a button that corresponds to a certain file is clicked, it will cancel the current request

Now I guess a small problem is how you get a button that corresponds to a file, but I think that wouldn't be too difficult. You could use, for example, @ViewChildren to get all the buttons, and by using the index in the mergeMap's projection function(2nd argument; mergeMap((val, idx) => ...)), you could identify a certain file.

Related