gpt4 book ai didi

Angular DI : Injecting a value token into factory provider

转载 作者:行者123 更新时间:2023-12-01 12:12:31 25 4
gpt4 key购买 nike

是否可以将 InjectionToken 注入(inject)工厂提供程序:

目前,我已经编码:

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
]
)

然而, Angular 正在注入(inject) configDataServiceProvider值(value) "host" , 而不是 "host-allianz"
有任何想法吗?

最佳答案

是的,您可以使用 @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]
};

Docs Here

关于 Angular DI : Injecting a value token into factory provider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50742028/

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