Search code examples
angulartypescripthttp-headersangular2-http

How to set a header with http.get


I'm using Angular 4.4.4 and I need to set the Authorization header for a GET request. I've studied the docs and the code to figure out how to do this. This was the result:

const headers = new Headers({ Authorization: this.auth.accessToken});
this.http.get('/api/Messages', { headers } as RequestOptionsArgs)

However, this doesn't work. The request is made without the header option.

But if I do it as follows

const options = { headers: {Authorization: this.auth.accessToken} as any};

return this.http.get('/api/Messages', options as RequestOptionsArgs)

It works.

But I would expect the first attempt to work too. Can someone explain to me what is wrong with my first attempt or explain to me what the correct approach is?


Solution

  • As explained in related question, the problem is that Fetch API has same class names as the classes from @angular/http module (their design is loosely based on Fetch API).

    If Angular classes (Header, Response, etc) weren't imported, global classes are used instead. This results in incorrect behaviour and irrelevant errors, because Angular classes aren't compatible with Fetch API, yet Http isn't fool-proof.

    The solution is to always import relevant classes together with Http (this can be done beforehand even if they aren't used):

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

    A way to avoid the problem is to switch to HttpClient which is available in latest Angular 4 releases and has different API.