是否可以将InjectionToken注入工厂提供者:
目前,我已编码:
export const HOST_TOKEN = new InjectionToken<string>("host");
let configDataServiceFactory = (userService: UserService, host: string) => {
return new Config("host", 8080, userService.getUser(), userService.getPasswd());
};
export let configDataServiceProvider =
{
provide: CONFIG_API,
useFactory: configDataServiceFactory,
deps: [UserService, HOST_TOKEN]
};
进入我的模块:
@NgModule(
providers: [
{provide: HOST_TOKEN, useValue: "allianz-host"},
configDataServiceProvider
]
)
尽管如此,角度注入configDataServiceProvider
值"host"
,而不是"host-allianz"
有什么想法吗?
答案 0 :(得分:2)
是的,你可以使用下面的@Inject
装饰器来做到这一点,这将帮助你从DI容器中提取相关的依赖。
let configDataServiceFactory = (userService: UserService, @Inject(HOST_TOKEN) host: string) => {
return new Config(host, 8080, userService.getUser(), userService.getPasswd());
};
您也可以考虑以下选项。基本上所有已注册的InjectionToken
都可以从应用程序Injector
中检索,这可以通过在get
实例上调用injector
方法并传递InjectorToken
名称来实现
export const HOST_TOKEN = new InjectionToken<string>("host");
let configDataServiceFactory = (userService: UserService, injector: Injector) => {
let host = injector.get(HOST_TOKEN); //retrieved token from injector
return new Config(host, 8080, userService.getUser(), userService.getPasswd());
};
export let configDataServiceProvider =
{
provide: CONFIG_API,
useFactory: configDataServiceFactory,
deps: [UserService, Injector]
};