如何从 Angular 拦截器中的服务获取数据?
How can I get data from service in Angular interceptor?
我想在我的 auth.interceptor.ts 中的请求 header 中添加我的身份验证令牌,并且我将身份验证令牌值保留在我的 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]
}
],
参考资料
我想在我的 auth.interceptor.ts 中的请求 header 中添加我的身份验证令牌,并且我将身份验证令牌值保留在我的 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]
}
],