我怎样才能从angular2的构造函数中传递字符串参数或数字 [英] how can I pass string parameter or number from constructor in angular2

查看:56
本文介绍了我怎样才能从angular2的构造函数中传递字符串参数或数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular2的打字稿中,我需要在构造函数中传递字符串参数或什至number参数,如下所示:构造函数(_para:string){}但是生成错误,调试器不断告诉我:

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 {消息:没有字符串提供者!(应用程序->字符串)",堆栈:错误:DIException↵在NoProviderError.BaseExc…ularjs.org/2.0.0-beta.8/angular2.dev.js:11284:19)"

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:

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

推荐答案

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

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.

诸如 string number boolean Object 之类的原始类型不能用作键.如果要使用此类泛型"类型,则需要一个人工密钥.除支持键外,DI还支持字符串或 OpaqueToken 作为键类型.对于此类人工键,您需要使用 @Inject()装饰器.

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

这篇关于我怎样才能从angular2的构造函数中传递字符串参数或数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆