我遇到jwt拦截器的怪异问题,在使用routerLink时会被跳过。
我有一个<a [routerLink]="['/users/history',user.id ]"> {{ user.id}}</a>
如果我单击html页面中的该链接,则会给我401未经身份验证的信息。如果通过URL http://localhost:4200/users/history/1
,它将加载良好。
我不知道为什么在使用routerLink加载页面时为何跳过jwt拦截器?
路线:
{
path: 'history/:id',
component: HistoryDetailsComponent,
canActivate: [AuthGuard]
}
拦截器:
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
有人可以帮我吗?
答案 0 :(得分:0)
将您interceptor
更新为此:
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
const cloned = request.clone({
// Use 'headers' instead of 'setHeaders'
// Use 'request.headers.set' to set the Authorization Bearer Token
headers: request.headers.set('Authorization', `Bearer ${currentUser.token}`)
});
return next.handle(cloned);
}
return next.handle(request);
}
}