在 angular2 for typescript 中,我需要在构造函数中传递字符串参数或偶数参数,如下所示:
构造函数(_para:字符串){}
但生成错误并且调试器不断告诉我:
NoProviderError {消息:“没有字符串的提供者!(应用程序 - >字符串)”,
堆栈:“错误:DI 异常↵位于
NoProviderError.BaseExc…ularjs.org/2.0.0-beta.8/angular2.dev.js:11284:19)"
如果我删除 _para:string ,它会起作用......
这是 plunker 中的恶魔:
http://plnkr.co/edit/t7serY3L6LtvzYc5xHtL?p=preview 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'
}
}
对于 Angulars 依赖注入 (DI) 创建的组件,它会尝试查找提供者并使用构造函数参数的类型作为查找提供者的关键。
原始类型如string
, number
, boolean
, Object
不能用作钥匙。如果您想使用此类“通用”类型,您需要一个人工密钥。 DI 支持字符串或不透明令牌 https://angular.io/docs/ts/latest/api/core/OpaqueToken-class.html作为类型之外的键。对于此类人工密钥,您需要使用@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'
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)