angular - 如何从 Angular 拦截器中的服务获取数据?
问题描述
我想在我的auth.interceptor.ts的请求标头中添加我的身份验证令牌,并且我将身份验证令牌值保留在我的auth.service.ts中。这是auth.interceptor.ts
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router,
private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('intercept', request);
const authReq = request.clone({headers: request.headers.set(this.authService.getAuthenticationKey(), this.authService.getAuthenticationToken())});
return next.handle(request);
}
}
这是auth.service.ts的一部分
...
public getAuthenticationToken(): string {
return this.authenticationToken;
}
public getAuthenticationKey(): string {
return this.authenticationKey;
}
...
这是我的app.module.ts
providers: [
{
provide: HTTP_INTERCEPTORS,
useFactory: (router: Router, authService: AuthService) => {
return new AuthInterceptor(router, authService);
},
multi: true,
deps: [Router]
}
],
但我得到这个错误
TypeError: Cannot read properties of undefined (reading 'getAuthenticationKey')
问题是什么?
解决方案
添加AuthService
到依赖项 ( deps
)。由于工厂函数可以访问AuthService
,您需要将其注入工厂提供程序。
providers: [
{
provide: HTTP_INTERCEPTORS,
useFactory: (router: Router, authService: AuthService) => {
return new AuthInterceptor(router, authService);
},
multi: true,
deps: [Router, AuthService]
}
],
参考
推荐阅读
- javascript - 对站点 json 进行排序并将所需信息存储到文件中
- laravel - 如何设置列标题以在刀片模板中使用它?
- javascript - 当使用来自 JS 的 Ajax 调用和在 JSP 中发送带有表单的 POST 时,返回“视图”的 Spring 代码的工作方式不同
- java - Java 多线程从内部类引用的局部变量必须是 final 或有效 final
- python - 将标准化从 Pandas 转换为 AWK 以提高性能
- java - 迁移 Playframework 2.4.3 到 2.7.0 中的问题
- windows - 如何从用户上下文执行 Add-LocalGroupMember 脚本包
- django - 即使启用了 xss,也会执行脚本
- python - 向网站发送发布请求时如何返回结果,然后选择其中一个?
- sql - 有没有办法在列表和标签上查询自定义表?