如何从 angular2 的构造函数传递字符串参数或数字

Nah*_*hed 2 typescript angular

在 typescript 的 angular2 中,我需要在构造函数中传递字符串参数或偶数参数,如下所示:constructor(_para:string) {} 但生成错误并且调试器不断告诉我:

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)"

如果我删除 _para:string ,它将起作用.... 这是 plnkr 中的 Demoe :

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'
  }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

对于由 Angulars 依赖注入 (DI) 创建的组件,它会尝试查找提供者并使用构造函数参数的类型作为关键来查找。

原始类型一样stringnumberbooleanObject不工作的按键。如果您想使用此类“通用”类型,则需要一个人工密钥。除了类型之外,DI 还支持字符串或OpaqueToken作为键。对于此类人工键,您需要使用@Inject()装饰器。

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'
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,我们相当过时的错误依赖注入文档的答案现在好多了。另请参阅 https://angular.io/api/core/InjectionToken (2认同)