我目前正在创建一个 Angular 库( Angular 7)。我需要将一些配置传递给模块,并且还需要调用函数“loadConfig”。问题是我无法在 loadConfig 函数中注入(inject)配置的值。
如果我尝试将其添加到 deps 数组并向函数添加参数,我将收到 nullinjector 错误。
我尝试添加一些控制台日志,并在 forRoot 方法中获取配置的值,并且在 SomeService 中我还获取配置的正确值。在 loadConfig 内部,我总是将配置设置为未定义。使用控制台日志,我发现 forRoot 方法是在 loadConfig 之前执行的,所以我很困惑为什么它不起作用。
你能帮我一下吗?
export function loadConfig() {
//some code
//if I add config as a parameter, the config here is undefined
}
export class SomeModule {
public static forRoot(config: any): ModuleWithProviders {
//if I console log here config is populated
return {
ngModule: SomeModule,
providers: [
SomeService,
{
provide: "config",
useValue: config,
},
{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [], //tried adding config here but get nullinjector error
multi: true,
}
],
};
}
}
export class SomeService {
constructor(@Inject("config") private config: any) {
//the config here is populated
}
}
最佳答案
我在您的代码中没有发现任何工作正常的主要问题。
我建议您使用存储在全局变量中的InjectionToken
。
这段代码对我来说就像一个魅力:
export const CONFIG_TOKEN = new InjectionToken('APP_CONFIG');
export function initConfig(config: any) {
return () => {...}
}
export class SomeModule {
public static forRoot(config: any): ModuleWithProviders {
return {
ngModule: SomeModule,
providers: [
{
provide: CONFIG_TOKEN,
useValue: config,
},
{
provide: APP_INITIALIZER,
useFactory: initConfig,
deps: [CONFIG_TOKEN],
multi: true,
}
]
};
}
}
关于Angular 库 - 使用 APP_INITIALIZER 将参数传递给服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62774098/