【发布时间】:2020-11-18 17:06:07
【问题描述】:
在我的 Angular 10 应用程序中,我的核心模块包含以下 2 个服务:
1.HttpResponseInterceptor - 拦截 http 响应,如果它的状态是 401 则重定向到某个登录页面。
@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor {
constructor(private configService: ConfigService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(error => {
if (!!error.status && error.status === 401) {
window.location.href = this.configService.getLoginPage();
return NEVER;
}
return throwError(error);
}));
}
2.ConfigService - 负责从文件系统加载配置文件和一些环境数据
@Injectable({providedIn: CoreModule})
export class ConfigService{
private readonly CONFIG_URL = 'assets/cfg.json';
public configuration: Configuration;
public wasEnvLoaded = false;
constructor(private httpClient: HttpClient) {
this.loadConfigurations();
}
public loadConfigurations(): any {
if (!this.configuration) {
this.httpClient.get<Configuration>(this.CONFIG_URL).subscribe((config: Configuration) => {
this.configuration = config;
this.wasEnvLoaded = true;
}
);
}
}
}
和我的核心模块:
@NgModule({
imports: [
HttpClientModule,
],
exports: [],
providers: [ {provide: HTTP_INTERCEPTORS, useClass: HttpResponseInterceptor, multi : true}],
declarations: []
})
export class CoreModule {
constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
if (parentModule) {
throw new Error('CoreModule is already loaded. Import only in AppModule');
}
}
}
我实施了here 提供的解决方案,一切正常。但是,我仍然在服务和核心模块之间收到循环依赖警告。谁能解释一下为什么?
export class HttpResponseInterceptor implements HttpInterceptor {
private loginPage: string;
private configurationLoaderService: ConfigurationLoaderService;
constructor(private injector: Injector) {
setTimeout(() => {
this.configurationLoaderService = this.injector.get(ConfigurationLoaderService);
this.loginPage = this.configurationLoaderService.configuration.cognitoLoginURL;
});
}
intercept(...){
错误:
循环错误:错误错误:无法实例化循环依赖!配置服务
【问题讨论】:
标签: angular