angular - Angular 库 - 使用 APP_INITIALIZER 将参数传递给服务
问题描述
我目前正在创建一个角度库(角度 7)。我需要将一些配置传递给模块,并且还需要调用函数“loadConfig”。问题是我无法在 loadConfig 函数中注入配置的值。
如果我尝试将它添加到 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,
}
]
};
}
}
推荐阅读
- windows - Jenkins Pipeline 不存储来自 cmd 文件的 Windows 环境变量
- deep-learning - 在每个 epoch 之后训练 MNIST 数据集时如何输出准确度和损失
- c++ - 如何在 C++ 中的最后一个数字/输出循环后删除逗号
- python - 将 dask 转换为 pandas 数据框
- c# - Powershell ProgramFiles 目录脚本
- blazor-client-side - 有东西阻塞了我的线程 - Blazor wasm
- sql - 检查是特定时间范围内的时间
- cordova - Cordova/Phonegap NFC 插件 NDEF_PUSH_DISABLED [已解决]
- actions-on-google - 有人可以帮助我更改我的调用短语吗?
- c++ - 什么时候可以创建“保留”标识符?