Ron*_*nin 6 angular-http-interceptors angular
因此,我使用如下基本拦截器创建了一个angular2模块来处理HTTP拦截:
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authService = this.injector.get(AuthService);
if(authService.isAuthenticated()){
const authReq = request.clone({
setHeaders: {
Authorization: `Bearer ${authService.getAccessToken()}`
}
});
let handle = next.handle(authReq).do(event => {
if(event instanceof HttpResponse){
if(event.headers.has('Authorization')){
authService.updateToken(event.headers.get('Authorization').split(' ')[1]);
}
}
});
return handle;
}else{
return next.handle(request);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当从服务器发送一个新的授权标头时,它将为http请求添加一个授权标头,并更新其自己的标头。它的导入和正常提供如下:
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
},
Run Code Online (Sandbox Code Playgroud)
因此,将auth angular2模块编译并导入到我的app.module.t中,效果很好。直到我尝试从子模块中使用它。此处的最高答案:Angular2中从父模块到子模块的继承导入声称angular2不会让您全局使用整个应用程序。它是否正确?
通过导入RequestInterceptor并在模块的提供程序中对其进行设置,我可以从子模块中获得该功能,但是我不想这样做,以使其使用起来不那么麻烦。
不是最好的答案-但是请检查此错误:https : //github.com/angular/angular/issues/20575
具体来说,注释如下:
您应该只导入一次HttpClientModule,请参阅docs
我想象您正在重新导入HttpClientModule
模块树中的某个位置-可能在另一个子模块中。如果只声明一次AppModule
(如果是,则声明一次),那么它应该在所有地方开始工作。无论如何,这就是我的经验。
这种臭味-并且当另一个开发人员稍后在ChildModule中将其导入时,已经很容易在以后引起错误,并且已经意识到拦截逻辑不再起作用。但这似乎就是这样。
归档时间: |
|
查看次数: |
2260 次 |
最近记录: |