我的Angular 4应用程序上有一个HttpInterceptor工作得非常好。但是我想要在这里实现的是在可用时注入JSON Web令牌,但我还没有找到正确的方法,请检查以下代码:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import {ToasterService} from "angular2-toaster";
import 'rxjs/add/operator/do';
@Injectable()
export class GobaeInterceptor implements HttpInterceptor {
constructor(private toasterService: ToasterService){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
next.handle(req).subscribe(event => {
if (event instanceof HttpResponse) {
if (localStorage.getItem('Token')) {
//THIS ISN'T WORKING:
event.headers.append('authentication', `${localStorage.getItem('Token')}`);
}
let response = event.body;
if(response.Error){
this.toasterService.pop('error', 'Error '+response.Code, response.Message);
}
}
}, error => {console.log(error)});
return next.handle(req);
}
}
它没有出现任何错误,但它也没有设置它(我检查了网络选项卡上的请求)。此外,我尝试传递一个硬编码字符串,而不是从localStorage获取相同的结果。
答案 0 :(得分:0)
我是这样做的:
export class JWTInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let headerName: string = 'Authorization';
let authScheme: string = 'Bearer ';
let token: string = localStorage.getItem('Token');
return next.handle(() => {
return request.clone({
setHeaders: {
[headerName]: `${authScheme}${token}`
}
});
});
}
}