Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@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.

like image 719
Alexey Nagornov Avatar asked May 17 '17 11:05

Alexey Nagornov


1 Answers

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

like image 171
Alexey Nagornov Avatar answered Nov 15 '22 02:11

Alexey Nagornov