6
votes

Recently I've run into problem with InjectionToken, that is declared in module

import {InjectionToken, NgModule} from '@angular/core';
import {SampleComponent} from './sample.component';

export let SOME_TOKEN = new InjectionToken<string>('someToken');

@NgModule({
  declarations: [SampleComponent],
  providers: [
    {provide: SOME_TOKEN, useValue: 'Some value'}
  ]
})
export class SampleModule {
}

And component class:

import {Component, Inject, OnInit} from '@angular/core';
import {SOME_TOKEN} from './sample.module';

@Component({
  selector: 'sample-component',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {

  constructor(@Inject(SOME_TOKEN) private someValue: string) { }

  ngOnInit() {
    console.log(this.someValue);
  }

}

All this gives me an error: Uncaught Error: Can't resolve all parameters for SampleComponent: (?).

At the same time if I try to use string as a token, that declared in module, everything works.

Also, if I declare InjectionToken directly at component file, and then set 'providers' directly inside component decorator, everything works again.

So the question is: why InjectionToken that is declared inside module file is not available for injection to component.

1
Move export let SOME_TOKEN = new InjectionToken<string>('someToken'); to separated file. You have circular dependency - yurzui

1 Answers

7
votes

According to @yurzui, there is a circular dependency. Moving token to separate file helped.