我正在尝试使用Angular 8中的APP_INITIALIZER通过服务加载配置文件(json)。配置包含缩略图的图像和道具的路径
app-config.json
{
"substitutePictureLink": "../images/not_found.png",
"noImageFound": "../images/404_not_found.png",
"thumbnailProps": {
"width": "400",
"height": "400",
"format": "PNG",
"view": "Interior",
"withdimensions": "true",
"withdescription": "true"
}
}
为了加载配置,我创建了一个服务[app-config-service],它看起来像这样:
app-config-service.ts
export class AppConfigService {
public get appConfig(): any {
return this._appConfig;
}
public set appConfig(value: any) {
this._appConfig = value;
}
private _appConfig: any;
constructor(
private _httpClient: HttpClient,
) {
console.log('constructor app-config-service');
this.loadAppConfig();
}
public loadAppConfig(): any {
//also tried a promise here
return this._httpClient.get('../../../assets/configs/app-config.json')
.pipe(
take(1)
)
.subscribe(
(config) => {
this._appConfig = config;
}
);
}
所以我需要在启动时加载配置;
app-module.ts
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
multi: true,
deps: [AppConfigService],
useFactory: (appConfigService: AppConfigService) => {
return () => {
return appConfigService.loadAppConfig();
};
}
}
],
bootstrap: [AppComponent],
})
export class AppModule {
}
当我尝试加载配置时,它看起来像这样:
some-service.ts
export class someService {
private _noImageFound = this._appConfigService.appConfig.noImageFound;
constructor(
private _appConfigService: AppConfigService
) {
}
...
public getThumbnail(): Observable<SafeUrl> {
return this._httpClient.get(this._apiUrl + '/visual-tree/thumbnail?width=400&height=400', {
responseType: 'blob',
})
.pipe(
map((res: Blob): SafeUrl => this._blobToUrl.transform(res)),
catchError((err: HttpErrorResponse): Observable<string> => {
this._logger.error(ErrorMessage.thumbnailNotLoaded, err);
return of(this._noImageFound);
})
);
}
...
错误:
此错误在登录后立即发生。有趣的是,app-config-service的构造函数被调用了两次。我的猜测是,该服务的引用发生了一些奇怪的事情。