angular - 如何以角度将拦截器范围限定为模块?
问题描述
以下是用于替换身份验证令牌的 Angular 拦截器。
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
) {
}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token: string = localStorage.get('token');
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
return next.handle(request);
}
}
我的应用程序是这样的结构:
--- app
---login // this is a routed module
---signup // this is a routed module
---main // this is a routed module
---profile // this is a routed child module
---items // this is a routed child module
身份验证令牌仅在登录后可用。
我正在为主模块设置拦截器(即在主模块中提供)(配置文件是用户登录后登陆并根据接收到的令牌发送请求的位置)
但这里的问题是拦截器在到达模块之前没有被调用。因此,当配置文件组件初始化并且OnInit()
我得到未验证响应时,当我检查控制台时,我可以看到授权标头未定义。
我该如何解决这个问题?
注意我没有提供它,root
因为这会在登录之前吐出 unauth 错误。所以我只在main.module.ts
文件中提供拦截器。
注意主模块没有任何组件。它仅用于注册配置文件模块和项目模块。
主模块是这样加载的(从根级别):
{
path: '',
loadChildren: () => import('./main/main.module').then((m) => m.MainModule),
canActivate: [AuthGuard],
},
解决方案
如果令牌可用,您可以添加这样的条件,然后添加令牌,否则请求不带令牌发送
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
) {
}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token: string = localStorage.get('token');
if(token && token.length){
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
}
return next.handle(request);
}
}
推荐阅读
- css - Ng 选择下拉菜单被对话框隐藏
- python - df 查询 Timedelta 列,其中持续时间 <= 1 小时
- c++ - 我的代码没有错误,但它不起作用
- python - SSHTunnelForwarder 是否支持 .ppk 扩展文件作为私钥?
- android - Android Studio 如何访问适配器类中的列表
- mysql - 在 Informatica 中将字符串转换为整数时不会出错
- jquery - 正则表达式所有字符加上一些标点符号
- webgl - Firefox 抛出错误 drawArraysInstanced: but attribs only supply 0, 当我在 Chrome 很好的情况下制作 drawArrays
- orbeon - 在 Orbeon 中使用特定版本的 Saxon
- python-3.x - Seaborn rugplot 没有情节