Robert Kusznier
Robert Kusznier

Reputation: 6911

How to inject a dependency into a provider with given injection token?

I'm using an Angular plugin, which needs to be configured by providing a configuration object using an InjectionToken that the plugin exports.

import { pluginToken } from 'plugin';

@NgModule({
  providers: {
    // Configure the plugin
    //
    // The configuration value string needs to be taken from some other
    // provider (available for dependency injection).
    { provides: pluginToken, useValue: valueString },
  },
})
class MyModule {
  ...
}

The problem I have is that valueString is a value from some other provider. I don't know how to inject a dependency into @NgModule decorator's provider. How it can be done?

Upvotes: 5

Views: 2398

Answers (2)

Reactgular
Reactgular

Reputation: 54751

The problem I have is that valueString is a value from some other provider

You can forward the value of one provider to another using useExisting

@NgModule({
    providers: [
        {provide: LOCALE_ID, useValue: 'en'},
        {provide: pluginToken, useExisting: LOCALE_ID},
    ],
})
export class MyModule {}

In the above example 'en' will be assigned to pluginToken because it uses the existing value of LOCALE_ID

Upvotes: 4

lealceldeiro
lealceldeiro

Reputation: 14958

Instead of useValue, inject the object instance by using useClass which

creates and returns new instance of the specified class


Code:

// ...
{ provides: pluginToken, useClass: YourConfigurationObjectClass },
//...

Upvotes: 1

Related Questions