简体   繁体   中英

Angular DI: Injecting a value token into factory provider

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM