为了避免循环依赖,我使用Injector
来注入AuthService
,但是当我运行应用程序Angular时,在设置intercept()
属性之前执行authService
方法! !
@Injectable()
export class TokenInterceptorService implements HttpInterceptor{
private authService;
constructor(private injector: Injector) {
setTimeout(() => {
this.authService = injector.get(AuthService);
console.log('===========================================',this.authService);
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.getToken()}`
}
});
return next.handle(request);
}
}
答案 0 :(得分:1)
setTimeout
不应该被用来避免循环依赖,因为它会导致像这样的竞争条件。
避免循环依赖的正确方法是就地检索它们。在拦截器类的情况下,它是intercept
方法:
export class TokenInterceptorService implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authService = this.injector.get(AuthService);
...
}
}
如果在由导致循环依赖的服务(AuthService
)执行的请求中有可能使用拦截器,则应该在拦截器中添加额外的安全措施以避免递归。