admin管理员组

文章数量:1406924

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 plete 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

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 plete 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

Share edited Feb 16, 2019 at 0:08 Ole asked Feb 15, 2019 at 1:38 OleOle 47.5k70 gold badges238 silver badges445 bronze badges 1
  • 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 Commented Feb 15, 2019 at 4:16
Add a ment  | 

1 Answer 1

Reset to default 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.ponent.ts

 constructor(@Inject(BASE_URL) configByToken) {
    console.log(configByToken);
  }

本文标签: javascriptInjection using an InjectionTokenStack Overflow