2
votes

In angular2 for typescript , I need to pass string parameter or even number parameter in the constructor as the following : constructor(_para:string) {} but generating an error and the debugger keep telling me :

NoProviderError {message: "No provider for String! (App -> String)", stack: "Error: DI Exception↵ at NoProviderError.BaseExc…ularjs.org/2.0.0-beta.8/angular2.dev.js:11284:19)"

if I remove _para:string , it will work .... here is the Demoe in plnkr :

http://plnkr.co/edit/t7serY3L6LtvzYc5xHtL?p=preview

and here is the code : 
//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>


    </div>
  `,
  directives: []
})
export class App {
  constructor(_para:string) {

    this.name = 'Angular2'
  }
}
1
Would be interesting how you want to use that parameter. The component instance is created by Angular for you. How should Angular know what to pass? See my answer, but I'm not sure if this is what you want. - Günter Zöchbauer

1 Answers

5
votes

For components created by Angulars dependency injection (DI), it tries to find providers and uses the type of the constructor parameters as key to find one.

Primitive types like string, number, boolean, Object don't work as keys. If you want to use such "generic" types you need an artifical key. DI supports a string or OpaqueToken as key in addition to types. For such artifical keys you need to use the @Inject() decorator.

bootstrap(MyApp, [provide('para': {useValue: 'Hello World!'})]);

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>


    </div>
  `,
  directives: []
})
export class App {
  constructor(@Injet('para') _para:string) {

    this.name = 'Angular2'
  }
}