0

I am learning the mean stack and I have a file I generate on the server-side of my application I intend to download this file from my angular front end when a button is clicked. but when I click the button nothing happens, I check my back end the file is generated successfully and everything works fine. when I access the 'localhost:port/generate-file' from my browser the file gets generated and downloaded successfully so I am thinking I have some issue on the angular part.

Here is the code I used :

ts

  downloadFile(): any {
    return this.http
      .get('http://localhost:4000/generated-file', { responseType: 'blob' })
      .subscribe();
  }

Markup

  <button class="button" (click)="downloadFile()">

Thank you in advance.

MARK
  • 75
  • 1
  • 11
  • 1
    First check if you're getting the response at the angular end by console.log, if yes then do subscribe to your response properly. I don't see anything after .subscribe(). Read abt how to subscribe the response. – Vinay Somawat Apr 21 '21 at 11:53
  • Hey @VinaySomawat thank you for your response, I console logged `console.log( this.http.get('http://localhost:4000/generated-file', { responseType: 'blob', })` and I got an observable object – MARK Apr 21 '21 at 11:59
  • You are doing it the wrong way! Read how to subscribe the response. https://stackoverflow.com/questions/51230312/angular-subscribe-response – Vinay Somawat Apr 21 '21 at 12:02

1 Answers1

0

If your API is working fine (if it is returning the file as blob), you can download it using file-saver.js.

this.http.get('http://localhost:4000/generated-file', {
    responseType: 'blob'
}).subscribe(
    response => {
        saveAs(response, 'filename')
    }
);

See this link for a simple example.

MonkeyScript
  • 4,776
  • 1
  • 11
  • 28