Angular 5 - How to use HTTPRespose.blob()?

724 views Asked by At

In Angular 4 , I used to download any excel or pdf file as a blob by making a http get or post call via the angular 4 http library .

My code in Angular 4 used to look like this :

import { Http, Response, Headers, RequestOptions,ResponseContentType   } from '@angular/http';
...................................

getExcelOrPDF(URL: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json' );        
    return this.http.get(URL, {headers: headers, responseType: ResponseContentType.Blob
  }).map(response => this.getData(response)) .catch(error => this.handleError(error));
}
    

    
    
public getData(res: Response) {
    console.log("getData()---Enter");
    let headers = res.headers;
    let contentType = headers.get('Content-Type');
    var blob;
    try {
        if(contentType === 'pdf' || contentType === 'application/pdf') {
            blob = new Blob([res.blob()], { type: "application/pdf"});
        } else {
            blob = new Blob([res.blob()], { type: "application/vnd.ms-excel"});
        }
    }
    catch (e) {
        console.debug(e);
    }
    console.log("getData()-Exit");
    return blob;
}

Now , we all know that in Angular 5 , we have support for HTTPClient Module and HTTPClient and I am trying to move away from angular 4 way of getting data . So , I have imported the HTTPClient, HTTPResponse etc.

My code in Angular 5 looks like this :

import { HttpClient, HttpResponse , HttpHeaders} from '@angular/common/http';
...................................

getExcelOrPDF(URL: string) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json' );        
    return this.http.get(URL, {headers : headers, responseType: 'blob' as 'json'
 }).map(response => this.getData(response)) .catch(error => this.handleError(error));
}
    

    
    
public getData(res: HttpResponse<any>) {
    console.log("getData()---Enter");
    let headers = res.headers;
    let contentType = headers.get('Content-Type');
    var blob;
    try {
        if(contentType === 'pdf' || contentType === 'application/pdf') {
            blob = new Blob([res.blob()], { type: "application/pdf"});
        } else {
            blob = new Blob([res.blob()], { type: "application/vnd.ms-excel"});
        }
    }
    catch (e) {
        console.debug(e);
    }
    console.log("getData()-Exit");
    return blob;
}

However , where the angular 4 code runs flawlessly, the above code in angular 5 gives me a couple of errors :

  • res.blob() --> Using HTTPResponse , I get the error : blob() function is not supported . This is an error that I get to see in the editor itself .
  • When the code is run , it compiles successfully , but when I try to download the excel , I get the error: unsupported media type : 415
  • I checked using console.logs , but it seems the function getData() is not even being called as the console logs are not getting printed .

Can some one please let me know as to what I am doing wrong here ? Any help is deeply appreciated .

1

There are 1 answers

0
The Dark Knight On BEST ANSWER

I had committed a silly mistake , due to which I was facing a lot of issues .

Firstly : When we are using HTTPClient instead of HTTP, we should create the headers like this :

let headers = new HttpHeaders();
headers  = headers.append('Content-Type', 'application/json' );

headers object is required to be assigned back to headers otherwise the actual headers object will be empty.

Secondly: make the http call like this : this.http.get(URL, {headers : headers, observe: 'response', responseType: 'blob'}

Thirdly : res.blob() is not available in HTTPResponse . Instead we should use : res.body

After going through hundreds of documentation and articles in the internet and countless trial and error , I was able to come up with a satisfactory solution .

Hopefully this helps anybody else who is going through a similar issue .