我试图让我的代码在 --aot 标志期间编译,但是在我尝试将环境配置加载到我在 app.module.ts 文件中导入的日志服务中时它失败了。我的代码看起来像这样,在“ng serve”下运行良好
这是我想要动态传递给我的单例日志服务的结构。
// In it's own ts file, not in the module
export interface AppConfiguration {
user: User;
application: ApplicationConfig;
}
// In it's own ts file, not in the module
export const appConfig = (): AppConfiguration => {
// ... logic happens here to set up the environment, load cookies etc that will result something like this
const userConf: User = {username: 'ronnrak', name: 'Ronny Raketgevär', id: 1, location: 'a place'};
const appConf: ApplicationConfig = {defaultLogLevel: 'debug', defaultLogType: 'console'};
return {user: userConf, application: appConf};
}
logging.module.ts:
export const APP_CONFIG = new InjectionToken<AppConfiguration>('app_config');
@NgModule({
imports: [CommonModule]
})
export class LoggingModule {
constructor(@Optional() @SkipSelf() parentModule: LoggingModule) {
if(parentModule) {
throw new Error('LoggingModule is already loaded, import in AppModule only.');
}
}
static forRoot(config: AppConfiguration): ModuleWithProviders {
return {
ngModule: LoggingModule,
providers: [
{provide: APP_CONFIG, useValue: config},
{provide: LoggingService, useFactory: (conf: AppConfiguration) => {
return conf.Application.defaultLogType === 'console' ? new ConsoleLoggingService(conf) : new RestLoggingService(conf);
}, deps:[APP_CONFIG]}
]
};
}
}
发生错误的 app.module.ts
const applicationConfigData: AppConfiguration = appConfig(); <-- error points here
@NgModule({
declarations: [
...
],
imports: [
...
LoggingModule.forRoot(applicationConfigData),
...
],
providers: [
{provide: APP_CONFIG, useValue: applicationConfigData},
{provide: StoreService, useFactory: (conf: AppConfiguration) => new StoreService(conf), deps: [APP_CONFIG]},
...
],
schemas: [
...
],
bootstrap: [
...
]
})
export class AppModule {}
这是我在运行 --aot 时遇到的错误
ERROR in apps\project\src\app\app.module.ts(17,49): Error during template compile of 'AppModule'
Function expressions are not supported in decorators in 'appConfig'
'appConfig' references 'appConfig'
'appConfig' contains the error at libs\environment\src\lib\init\app-init.ts(19,26)
Consider changing the function expression into an exported function.
我试图在没有 lambda 表达式的情况下更改 appConfig,而只是一个明确的导出函数,但它也不起作用。
ERROR in apps\project\src\app\app.module.ts(17,49): Error during template compile of 'AppModule'
Function calls are not supported in decorators but 'appConfig' was called.
如何从 app.module 将动态数据加载到我的单例服务中?