Angular 2 passing parameters to constructor throws DI exception

Simon Trewhella picture Simon Trewhella · Feb 20, 2016 · Viewed 19.3k times · Source

I'm wanting to setup a string property on a component in my constructor, but when I try something like this

@Component({
    selector: 'wg-app',
    templateUrl: 'templates/html/wg-app.html'
})
export class AppComponent {

    constructor(private state:string = 'joining'){

    }
}

I get a DI Exception

    EXCEPTION: No provider for String! (AppComponent -> String)

Clearly, the injector is trying to find a 'string' provider, and can't find any.

What sort of pattern should I be using for this type of thing? Eg. passing initial parameters to a component.

Should it be avoided? Should I be Injecting the initial string?

Answer

Sasxa picture Sasxa · Feb 20, 2016

You can use @Input() properties.

<my-component [state]="'joining'"></my-component>

export class AppComponent {
  @Input() state: string;
  constructor() { 
    console.log(this.state) // => undefined
  }
  ngOnInit() {
    console.log(this.state) // => 'joining'
  }
}

Constructor should generally be used just for DI...

But if you really, really need it you can create injectable variable (plunker):

let REALLY_IMPORTANT_STRING = new OpaqueToken('REALLY_IMPORTANT_STRING');
bootstrap(AppComponent, [provide(REALLY_IMPORTANT_STRING, { useValue: '!' })])

export class AppComponent {
  constructor(@Inject(REALLY_IMPORTANT_STRING) public state: REALLY_IMPORTANT_STRING) { 
    console.log(this.state) // => !
  }
}

Simplest option is to just set class property:

export class AppComponent {
  private state:string = 'joining';
  constructor() { 
    console.log(this.state) // => joining
  }
}

As @Mark pointed out, another option is to use a service:

export class AppService {
  public state:string = 'joining';
}
export class AppComponent {
  constructor(private service: AppService) { 
    console.log(this.service.state) // => joining
  }
}