intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let request = req.clone({
setHeaders: this.getRequestHeaders()
});
return next.handle(request).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse && event.status==200) {
} else
console.log('event =', event, ';');
return event;
})
.catch((err: any, caught) => {
if (err instanceof HttpErrorResponse) {
let error=err['error']
// if (err['error'] && (err['error']['status'] == 401) && (err['error']['message']=="Session Expired,please login Again.") || err['error']['message']=="Full authentication is required to access this resource") {
// setTimeout(()=>{
// this.localStorageService.clearLocalStorage();
// return this.router.navigate(['/login']);
// }, 1000);
// }
return Observable.throw(error);
}
});
}
public getRequestHeaders(){
let token=this.localStorageService.getToken();
let headers={'Accept': 'application/json'};
if(token){
headers['Authorisation']=token;
}
return headers;
}
我已经实现了拦截器服务,但是令牌没有传入 传入标题,因此没有任何效果。我拿来 来自本地存储的令牌,但没有显示任何内容
答案 0 :(得分:0)
为了设置标题,您必须创建这样的标题实例。以下是我的示例
private initAuthHeaders(): Headers {
const token = this.getLocalToken();
const headers = new Headers();
if (token !== null) {
headers.append('Authorization', 'Bearer ' + token);
}
headers.append('Content-Type', 'application/json');
return headers;
}