Reputation: 850
I am learning Angular 2 and I am trying to Download the Excel file in angular 2 by fetching customer data from sql server tables using web api.
After searching in google i found some code but using that code i am able to download but it does not contain the proper data and file name is also having some guid format
Below is the code i have used:
Component
GetRemindersData()
{
var Flag="ALL_SPOTCHECK_RECORDS";
this.httpService.GetRemindersData(Flag).subscribe(
data=>this.downloadFile(JSON.stringify(data[1])),
error => console.log("Error downloading the file."),
() => console.info("OK"));
}
downloadFile(data:any){
console.log(data);
var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
var url= window.URL.createObjectURL(blob);
window.open(url);
}
Service.ts
public GetRemindersData(Flag:string){
var GetRemindersData_URL:string = 'http://localhost:5000/api/RemindersData/?Flag='+Flag;
return this.http.get(`${GetRemindersData_URL}`)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
Upvotes: 0
Views: 10169
Reputation: 3483
Service return json ,it must return blob type,you can do like that
return this.http.get(url,{responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/vnd.ms-excel' })
})
Also look at this post angular2 file downlaod
Upvotes: 1