0

I am trying to grab the local storage variable and send it inside of a GET HTTP request inside of the headers, but when it hits the API the token is null. I console log the token and it shows up just fine. I'm not sure what I'm doing wrong. Help is appreciated.

getUserByToken(): Observable<User> {
 const userToken = localStorage.getItem('authToken');
  
 console.log(userToken);//displays just fine
  
 const httpHeaders = new HttpHeaders();
 httpHeaders.append('Authorization', 'Bearer ' + userToken);//Shows up null 
  
 console.log('Bearer ' + userToken);//logs just fine 
  
 httpHeaders.append('Content-Type', 'application/json'); 
    
 return this.http.get<User>(API_USERS_URL, { headers: httpHeaders });
}
Stephen Romero
  • 2,812
  • 4
  • 25
  • 48

1 Answers1

1

append returns a clone of the headers. You need to set the returned value to the headers.

httpHeaders=httpHeaders.append..

And by the way. If you intend to do this on a lot of calls. Move this code into the angular interceptor. https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

Jens Alenius
  • 1,931
  • 2
  • 16
  • 20