Angular DI:将值令牌注入工厂提供程序

时间:2018-06-07 13:05:31

标签: angular typescript dependency-injection

是否可以将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"

有什么想法吗?

1 个答案:

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

Docs Here