Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 HttpHeaders are empty

I understand that HttpHeaders are immutable. I've tried several different ways to initialize them, or append to them, but when I log them it always shows they are empty.

I've tried initializing them with all values:

const headers = new HttpHeaders({
  'Authorization': `Bearer ${this.auth.accessToken}`,
  'Content-Type': 'application/json'
});

And I've tried setting:

let headers = new HttpHeaders();
headers = headers.set('Authorization', `Bearer ${this.auth.accessToken}`);
headers = headers.set('Content-Type', 'application/json');

And I've tried appending:

let headers = new HttpHeaders();
headers = headers.append('Authorization', `Bearer ${this.auth.accessToken}`);
headers = headers.append('Content-Type', 'application/json');

But all result in empty headers and the API says it was unable to find any authorization token.

Console output:

Console output of http headers

What am I doing wrong?

like image 202
Trevor Avatar asked Feb 26 '19 02:02

Trevor


1 Answers

This is probably due to lazy parsing, you have to do a get to access values. Not implemented as a key - value pair.

HttpHeaders class represents the header configuration options for an HTTP request. Instances should be assumed immutable with lazy parsing.

Do console.log(headers.getAll('Authorization'))

But, to make sure headers are sent, a better place to check will be Network tab in DevTools.

like image 140
sabithpocker Avatar answered Oct 18 '22 01:10

sabithpocker