0

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.

1

4 Answers 4

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

0

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
}

Comments

0

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});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.