我试图包括访问令牌到我的HTTP请求。我把它保存到本地存储,并保存为一个对象。如何检索令牌以便将其放入HTTP授权头
这是我的登录组件。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);
}
}
如果你有答案,请给我留言或评论。我知道这是一个简单的问题。我非常感谢你们的回复。谢谢你
首先,getItem("'token")
有太多,它需要getItem("token")
。
其次,只有在创建拦截器时才从localStorage读取令牌。
您是否尝试在拦截函数本身中加载令牌?
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
}
应该可以。另外,不要使用localStorage来获取/设置令牌,你可能想要使用一个同时注入到Interceptor和LoginService中的Service,比如TokenService。