Angular DI:将价值代币注入工厂提供商 [英] Angular DI: Injecting a value token into factory provider

查看:79
本文介绍了Angular DI:将价值代币注入工厂提供商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将InjectionToken注入工厂提供者中?

Is it possible to inject an InjectionToken into a factory provider:

当前,我已将其编码为:

Currently, I've coded that:

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 值上主机 ,而不是主机-allianz

Nevertheless, angular is injecting on configDataServiceProvider value "host", instead of "host-allianz"

有什么想法吗?

推荐答案

是的,您可以使用 @Inject 如下所示的装饰器,它将帮助您从DI容器中提取相关的依赖项。

Yes, you can do that using @Inject decorator like below, which will help you to extract the relevant dependency from DI container.

let configDataServiceFactory = (userService: UserService, @Inject(HOST_TOKEN) host: string) => {
    return new Config(host, 8080, userService.getUser(), userService.getPasswd());
};






您也可以考虑以下选项。基本上,所有已注册的 InjectionToken 都可以从应用程序 Injector 中检索,这可以通过调用<$ c来实现$ c> get 方法通过 injector 实例并传递 InjectorToken 名称。


You can also consider below option as well. Basically all registered InjectionToken's would be available to retrieve from application Injector, that can be achieve by calling get method over injector instance and pass InjectorToken name.

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]
};

此处的文档

这篇关于Angular DI:将价值代币注入工厂提供商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆