Reputation: 97
I am trying to set headers for one of the get request. Following is the function:
getLeads(jwtToken: string): Observable<any>{
const headers = new HttpHeaders();
const authroizationToken = 'bearer '.concat(jwtToken);
console.log(authroizationToken); ------------------> prints the token
headers.append('Authorization', authroizationToken);
console.log(headers.get('Authorization')); ---------------------> this prints null
var result = this.http.get<Leads>(this.getLeadsUrl, {headers});
return result;
}
But heades.get('Authorization') is null for some reason and I am not able to figure out why. Any help would be much appreciated.
Upvotes: 0
Views: 1384
Reputation: 22213
You can use set()
method of HttpHeaders:
Which sets or modifies a value for a given header in a clone of the original instance. If the header already exists, it's value is replaced with the given value in the returned object.
An example:
let header = new HttpHeaders().set(
"Authorization",`bearer ${jwtToken}`
);
return this.http.get<Leads>(this.getLeadsUrl, {headers:header});
Upvotes: 0
Reputation: 331
The question has answers in the following threads.
https://stackoverflow.com/a/45286959/12376898
https://stackoverflow.com/a/47805759/12376898
To sum it up, the headers are immutable, hence making any changes creates a new object. Unless you reference the newly created object to the old reference, only the old object persists.
getLeads(jwtToken: string) {
let headers = new HttpHeaders();
headers.append('ANYHEADER','SOMESTRING') // will be lost
headers = headers.append('ANYHEADER','SOMESTRING') //unless you reference it again to the old reference
}
Upvotes: 0
Reputation: 5056
Actually .append
returns the new headers objects. try this it works as expected. Just make sure you assign the headers back to the variable everytime you append a new header.
getLeads(jwtToken: string) {
let headers = new HttpHeaders();
const authroizationToken = 'bearer '.concat(jwtToken);
console.log(authroizationToken);
headers = headers.append('Authorization', authroizationToken);
console.log(headers.get('Authorization'));
}
Here is a working Stackblitz
Hope this helps :)
Upvotes: 1
Reputation: 6169
Make the following changes to your code:
getLeads(jwtToken: string): Observable<any>{
let httpOptions = {
headers: new HttpHeaders({ 'Authorization': `bearer ${jwtToken}` })
};
return this.http.get<Leads>(this.getLeadsUrl, httpOptions);
}
Upvotes: 0