Alexey Nagornov
Alexey Nagornov

Reputation: 131

@Inject() for InjectionToken declared in module fails in angular2

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.

Upvotes: 6

Views: 5457

Answers (1)

Alexey Nagornov
Alexey Nagornov

Reputation: 131

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

Upvotes: 7

Related Questions