Angular DI: Injecting a value token into factory provider

元气小坏坏 提交于 2020-06-25 21:51:50

问题


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

Into my module:

@NgModule(
  providers: [
    {provide: HOST_TOKEN, useValue: "allianz-host"},
    configDataServiceProvider
  ]
)

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

Any ideas?


回答1:


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());
};

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

Docs Here



来源:https://stackoverflow.com/questions/50742028/angular-di-injecting-a-value-token-into-factory-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!