Search code examples
angulartypescriptangular2-servicesangular4-httpclient

Error in adding headers to http.get in Angular 4


I'm trying the following code:

  let myHeader = new HttpHeaders();
    myHeader.append("Authorization", Token);
    return this.http
      .get(this.service.GetDomainPrefix() + "Source/Download/" + id, 
        {       
          headers: myHeader, responseType: ResponseContentType.Blob
    }).map(res => {
    return {
      filename: name + '.mp4',
      data: res.blob()
    };
  })

but getting the following error:

Argument of type '{headers: HttpHeaders; responseType: ResponseContentType.Blobl;}' is not assignable to parameter of type 'RequestOptionsArgs'. Type 'HttpHeaders' is not assignable to type 'Headers'

The problems is only with the headers, because without it there are no errors. How can I add a head to my get request?


Solution

  • It's probably because you are using HttpModule (angular 2,4) instead of the new HttpClientModule (angular 4,5,6) (and the Http class instead of HttpClient class)

    Also, HttpHeaders are immutable. To use the new HttpClientModule, use this code

    import {HttpClient, HttpHeaders} from '@angular/common/http';
    
    constructor(private http: HttpClient){}
    //...
    let myHeader = new HttpHeaders().append("Authorization", Token);
        return this.http
          .get(this.service.GetDomainPrefix() + "Source/Download/" + id, 
            {       
              headers: myHeader, responseType: 'blob'
        })
    .map(res =>  {
          filename: name + '.mp4',
          data: res
              })
    

    And you need to modify your AppModule to import HttpClientModule instead of HttpClient