简体   繁体   English

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

[英]how can I pass string parameter or number from constructor in angular2

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 : 在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)" NoProviderError {消息:“没有字符串提供者!(应用程序->字符串)”,堆栈:“错误:DIException↵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 : 如果我删除_para:string,它将起作用.....这是plnkr中的Demoe:

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

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'
  }
}

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. 对于由Angulars依赖项注入(DI)创建的组件,它将尝试查找提供程序,并使用构造函数参数的类型作为键来查找一个。

Primitive types like string , number , boolean , Object don't work as keys. 诸如stringnumberbooleanObject类的原始类型不能用作键。 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. 除类型外,DI还支持字符串或OpaqueToken作为键。 For such artifical keys you need to use the @Inject() decorator. 对于此类人为键,您需要使用@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'
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM