How to get just the token so I can use it in my HTTP header

Viewed 32

Im trying to include the access token to my HTTP request. I saved it to local storage and it saved as an object . How can I retrieve just the token so I can put it in my HTTP Authorization header

This is my login component.ts

       import { Component, OnInit } from '@angular/core';
      import { HttpClient } from '@angular/common/http';
       import { Router } from '@angular/router'
         import {LoginServiceService} from 'src/app/login-service.service'
      import { NgForm } from '@angular/forms';

        @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
      })
      export class LoginComponent implements OnInit
        {

    response: any;
      constructor(private http: HttpClient, private router: Router, public 
  LoginService:LoginServiceService) { }

      ngOnInit(): void {

   }

    login(newFormdata:any)
       {

      this.LoginService.login(newFormdata).subscribe((data) =>
      {
      console.log(data)
      localStorage.setItem("token",JSON.stringify(data))
      this.router.navigate(['facility-list'])
      })
      }  
      }

 This is my Login service

 export class LoginServiceService {

  constructor( private http:HttpClient,private router:Router) { }

  login(information:any)
  {
  return this.http.post("http://localhost:8000/api/login", information)
  }
  }

  This is the http interceptor

   export class AppinterceptorInterceptor implements HttpInterceptor {

   constructor() { }
   token = localStorage.getItem("'token")
   intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
   {
   let tokenizedRequest = request.clone({
   setHeaders: {
     Authorization: 'Bearer ' + this.token
   }
  })

return next.handle(tokenizedRequest);

 }
}

Please send me a message or comment if you have answer . I know that this is an easy question . I ahighly appreciate your responses guys . Thank you

1 Answers

First, getItem("'token") has an ' too much, it needs to be getItem("token").

Secondly, you only read the token from localStorage when the Interceptor is created.

Have you tried to load the token in the intercept function itself?

   intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
   {
   if (!this.token) { this.token = localStorage.getItem("token"); }
   let tokenizedRequest = request.clone({
   setHeaders: {
     Authorization: 'Bearer ' + this.token
   }

That should work. Also, instead of using the localStorage to get / set the token, you might want to use a Service that is injected into both the Interceptor and the LoginService, such as a TokenService.

Related