我有一个循环依赖项(在运行时!)问题,我不知道该怎么解决。
我已经注册了一个APP_INITIALIZER加载函数,它加载一个config.json文件。此配置文件除其他外包含LogLevel
for NGXLogger
。配置文件通过角的HttpClient
加载。
除此之外,我注册了一个HttpInterceptor
,它使用NGXLogger
。
似乎角试图按照这个顺序来解决所有的问题:
APP_INITIALIZER
,所以首先运行这个函数http
调用,所以首先通过拦截器运行HttpInterceptor
=> NGXLogger
的加载依赖项NGXLogger
=>中的配置文件为APP_INITIALIZER
配置提供程序如何解决这个循环依赖关系?有没有办法完全跳过APP_INITIALIZER
http调用上的拦截器?
CoreModule.ts:
export function appConfigFactory(configService: AppConfigService) {
return () => configService.load();
}
export function loggerConfigFactory(configService: AppConfigService): {
return () => {
level: (NgxLoggerLevel as any)[configService.config.logLevel] || NgxLoggerLevel.ERROR,
};
}
@NgModule({
...
providers: [{
provide: APP_INITIALIZER,
useFactory: appConfigFactory,
deps: [AppConfigService],
multi: true
}, {
provide: NgxLoggerConfig,
useFactory: loggerConfigFactory,
deps: [AppConfigService]
}]
})
export class CoreModule {}
AppConfigService.ts:
export class AppConfigService {
constructor(private http: HttpClient) {}
load() {
return this.http
.get<AppConfig>(`/assets/configuration/${environment.configFile}`)
.pipe(
tap((config: any) => {
this.config = config;
})
)
.toPromise();
}
}
FakeBackendInterceptor:
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
constructor(private configService: AppConfigService, private logger: NGXLogger) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// config is undefined here the first time
if (!this.configService.config || !this.configService.config.mock === 'true') {
return next.handle(request);
}
this.logger.info('Intercepting request with mock');
// do things
...
return next.handle(request);
}
}
发布于 2019-09-09 01:33:44
可以使用HttpBackend
跳过配置服务中的拦截器。
constructor(
private http: HttpClient,
private httpBackend: HttpBackend) { }
在荷载法中
const httpClient = new HttpClient(this.httpBackend);
httpClient.get<AppConfig>(`/assets/configuration/${environment.configFile}`)
.pipe(
tap((config: any) => {
this.config = config;
})
)
.toPromise();
https://stackoverflow.com/questions/57850927
复制