【发布时间】:2018-01-16 23:00:03
【问题描述】:
我刚刚将我的 Angular 应用程序从 v4 迁移到 v5,我必须重写我的拦截器(通过扩展 Http 并覆盖 request 方法)以使用 HttpInterceptor 接口。
我要做的是拦截带有 201 响应代码的请求,用响应的标头更新请求的标头,执行更新的请求并返回新的响应。
我的代码目前看起来像这样:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const handled = next.handle(req);
return handled.mergeMap(event => {
// I only work when the response is arrived
if (event.type === HttpEventType.Response) {
// The 201 status code tells me I have to update my headers
if (event.status === 201 && event.url.split('/').pop().toLowerCase() !== 'check') {
this.authService.updateAuthentication(event.headers.get('new_token')); // update the cookie containing the token
// I create the updated request
const requestWithUpdatedHeaders = req.clone({ headers: this.appService.getHeaders() });
// With this solution, the new request doesn't seem to be performed at all
return next.handle(requestWithUpdatedHeaders);
// With this one the request is performed but the result get in my components is null
return this.http.request(requestWithUpdatedHeaders);
} else {
return handled;
}
} else {
return handled;
}
});
}
我怎样才能做到这一点?
【问题讨论】:
标签: angular http interceptor angular5