【发布时间】:2018-12-29 01:28:07
【问题描述】:
在过去的两天里,我使用 Angular 6 尝试了许多不同的方法,这篇文章的最新版本是:https://stackoverflow.com/a/47401544。但是,仍然没有在请求上设置标头。
import {Inject, Injectable} from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do((event: HttpEvent<any>) => {
if (localStorage.getItem('id_token') != null) {
// Clone the request to add the new header.
const request = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
'Authorization': `Bearer ${localStorage.getItem('id_token')}`
}
});
return next.handle(request);
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log('redirect auth interceptor')
// do a redirect
}
}
});
}
}
如果我注销 request,request.headers.lazyUpdate 数组将更新 3 个项目,但我在它拦截的请求中看不到 Authorization 标头。
request.headers.lazyUpdate:
{name: "Content-Type", value: "application/json; charset=utf-8", op: "s"}
{name: "Accept", value: "application/json", op: "s"}
{name: "Authorization", value: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2Mzh9.tLTmPK46NhXSuqoCfZKgZcrQWzlNqLMI71-G0iy3bi8", op: "s"}
(request.headers.headers 是空的——这可能是问题吗?)
app.module.ts:
providers: [
{provide: HTTP_INTERCEPTORS, useClass: AuthTokenInterceptor, multi: true},
],
让我认为这是一个拦截器问题的原因是,如果我手动将标头添加到请求中,我不会得到 401 并且请求会返回正确的数据和 200:
return this.http.get(environment.API_URL + 'list/supervise/' + encodeURIComponent(id),
{headers: new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem('id_token')}`)}).pipe(
map((res: any) => res.data)
);
有什么我可能忽略的吗?谢谢。
编辑:
正如我在下面的评论中提到的,我两次返回 next.handle。这是我最终采用的解决方案:
import {Injectable} from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('id_token');
req = req.clone({
setHeaders: {
'Authorization': `Bearer ${token}`
},
});
return next.handle(req);
}
}
【问题讨论】:
标签: angular typescript