3

Attempting to inject an object using an InjectionToken.

In the AppModule I have:

    export const tokenConfigKey = new InjectionToken('config');

    const tokenBasedConfig = {
        provide: tokenConfigKey,
        useValue: {
          key: 'value'
      }
    }

And in the AppComponent:

    @Component({
      selector: 'my-app',
      template:`<h1>Hello Angular Lovers!</h1>`
    })
    export class AppComponent  {
      constructor(@Inject('config') config,
                  @Inject(tokenConfigKey) configByToken) {
      }
    }

This is a complete stacblitz example

Injection using the string key is passing, but injection with the token is failing. Any ideas why?

Article

Here's an article in case anyone wants to play with this

Ole
  • 41,793
  • 59
  • 191
  • 359
  • Are you using the same instance of the injection token? In other words, do you have something like... `import { tokenConfigKey } from '/path/to/app.module'`? – Pace Feb 15 '19 at 04:16

1 Answers1

6

A circular dependency issue could exist due to the fact that the AppModule imports the AppComponent and the AppComponent imports the InjectionToken from the AppModule.

Moving token to separate resolvs the issue:

token.ts

import { InjectionToken } from '@angular/core';
export const BASE_URL = new InjectionToken<string>('BaseUrl');

app.module.ts

@NgModule({
  providers: [{ provide: BASE_URL, useValue: { key: 'http://localhost' } }],

app.component.ts

 constructor(@Inject(BASE_URL) configByToken) {
    console.log(configByToken);
  }
Ole
  • 41,793
  • 59
  • 191
  • 359
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • This is the updated stackblitz in case anyone wants to see: https://stackblitz.com/edit/angular-configuration-injection2?file=src%2Fapp%2Fapp.component.ts – Ole Feb 15 '19 at 20:51
  • I moved the InjectionToken to the `AppComponent` and exported it from there that way there are only two files and no circular dependency. – Ole Feb 15 '19 at 23:46