2

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
  • 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. Commented Apr 5, 2016 at 5:56

1 Answer 1

5

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'
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The answer us quite outdated bug dependency injection docs are much better now anyway. See also angular.io/api/core/InjectionToken
I've noticed! ;-) But it's small changes... Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.