gpt4 book ai didi

Angular aot 构建 : dynamic forRoot parameter results in undefined

转载 作者:行者123 更新时间:2023-12-04 01:56:33 26 4
gpt4 key购买 nike

我需要向功能模块中的服务发送配置(对象数组),并且需要动态计算此配置。我使用了 forRoot,在我使用 --aot 构建它之前,它工作正常。

问题:使用--aot,配置结果为undefined

这是我在 stackblitz 上制作的示例的链接: https://stackblitz.com/edit/angular-aot-forroot-error

<强>!!它在 stackblitz 上按预期工作,因为它不是用 aot 构建的!! 如果你用 aot 在本地构建它,GetConfigService 将抛出一个错误,因为 config 将是未定义的。

重要部分:

应用模块:

export const config = [
{
id: 'first'
},
{
id: 'second'
}
];

// just illustrative modification (in my project I need to modify config based on environment)
export function modifyConfig(config) {
return config.map(c => c.id === 'first' ? {...c, default: true} : c);
}

const configModified = modifyConfig(config);

@NgModule({
imports: [
BrowserModule,
WithParametersdModule.forRoot(configModified)
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

WithParametersdModule:

@NgModule()
export class WithParametersdModule {
static forRoot(config) {
return {
ngModule: WithParametersdModule,
providers: [
{
provide: SOME_CONFIG,
useValue: config
},
GetConfigService
]
}
}
}

获取配置服务:

@Injectable()
export class GetConfigService {

constructor(@Inject(SOME_CONFIG) private config) {}

get configObj() {
if (!this.config) {
throw `config: ${this.config}`;
}

return this.config;
}
}

感谢您的帮助或对我做错了什么的解释。

最佳答案

我发现这可能是因为 AOT 会尝试在编译时替换 useValue,但是当您在运行时传递这些值时,所以 AOT 只是将其替换为 undefined。解决方案是使用 useFactory 而不是 useValue。这解决了这个问题。

这是我做的:

// Declare a function type which returns the config
export type ConfigFunction = () => any;

// Replace useValue with useFactory
@NgModule()
export class WithParametersdModule {
static forRoot(config: {
func: ConfigFunction,
// You could add other config parameters here...
}) {
return {
ngModule: WithParametersdModule,
providers: [
{
provide: SOME_CONFIG,
useFactory: config.func
},
GetConfigService
]
}
}
}

然后你可以像下面这样使用它:

export function getConfig(): any {
return {
id: 'first'
},
{
id: 'second'
};
}

@NgModule({
// ...
imports: [
BrowserModule,
WithParametersdModule.forRoot({ func: getConfig }),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

关于 Angular aot 构建 : dynamic forRoot parameter results in undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50131083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com