1
votes

I have to download csv file using HttpClient in angular 6 inside browser itself when user will click on download method.

component.service.ts

download():Observable<any[]>{
  return this.http.get<any[]>(this.url+'/download/external');
}

compononent.ts

    onDownload(){
    console.log("data is downloading");
    this.service.download().subscribe(data=>{
    let dataType = data;
        let binaryData = [];
        binaryData.push(data);
        let downloadLink = document.createElement('a');
        downloadLink.href = window.URL.createObjectURL(new 
        Blob(binaryData, {type:"application/ms-excel"}));
         document.body.appendChild(downloadLink);
        downloadLink.click();
     })

   }

In response I am getting this error:

ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/expocms/download/external", ok: false, …}

1

1 Answers

0
votes

you can try like this

onDownload(){
console.log("data is downloading");
   this.service.download().subscribe(response=>{
    const a = document.createElement('a');
    document.body.appendChild(a);
    const blob = new Blob([response], { type: 'octet/stream' });
   // if octet/stream is not working then try this one application/ms-excel
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = "filename.csv"; // you need to write the extension of file here
    a.click();
    window.URL.revokeObjectURL(url);
 })
}

let me know if it is working or not