Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 963
Robert Kusznier Avatar asked Aug 29 '18 14:08

Robert Kusznier


1 Answers

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

like image 157
Reactgular Avatar answered Sep 28 '22 18:09

Reactgular