Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injection using an InjectionToken?

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

like image 218
Ole Avatar asked May 14 '26 03:05

Ole


1 Answers

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);
  }
like image 121
Pranay Rana Avatar answered May 16 '26 17:05

Pranay Rana