Search code examples
angularangular-httpclient

Angular HttpHeaders is not setting value


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.


Solution

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