I'm using angular2-http(alpha.44) module to retrieve data from a REST Api. I can't figure out how to access the information that comes in the headers map of the response, from which I need a specific field. Example:
var req = new Request({
url: `localhost/api/products`,
method: RequestMethods.Get
});
this.http.request(req).subscribe(
res => {
// Can't access the headers of the response here.... res.headers is empty
},
error => { ... },
_ => {}
);
Strangely enough, if I check the network traffic in the browser's dev tools, the response headers are present...
There is already an issue about that problem opened on github:-
https://github.com/angular/angular/issues/5237#issuecomment-156059284
Please check it, as someone posted a workaround.
UPDATE
The angular team has already solved this problem.
The solution is in the already linked issue but in a later comment: https://github.com/angular/angular/issues/5237#issuecomment-239174349
Except for some generic headers only the headers listed as a value of Access-Control-Expose-Headers
header will be mapped in Angular2 (maybe with others too). This has to be added on backend side.
For me it took more than an hour to find this out for Authorization
header. I thought it is not that custom header but it is.
In PHP call something like this:
header("Access-Control-Expose-Headers: Authorization, X-Custom-header");
If you use Laravel as backend with barryvdh/laravel-cors
do this setup in the config/cors.php
file.
I found this link helpful:
https://developer.mozilla.org/es/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
Where as I had to specify what the necessary headers I had to expose to the End user from my Server itself by adding what the header(s) really were!
// Request headers you wish to expose
res.setHeader('Access-Control-Expose-Headers', 'your_desired_header, content-type');
Cheers!