Angular 2 向构造函数传递参数会引发 DI 异常 [英] Angular 2 passing parameters to constructor throws DI exception

查看:30
本文介绍了Angular 2 向构造函数传递参数会引发 DI 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的构造函数中的一个组件上设置一个字符串属性,但是当我尝试这样的事情时

I'm wanting to setup a string property on a component in my constructor, but when I try something like this

@Component({
    selector: 'wg-app',
    templateUrl: 'templates/html/wg-app.html'
})
export class AppComponent {

    constructor(private state:string = 'joining'){

    }
}

我收到 DI 异常

    EXCEPTION: No provider for String! (AppComponent -> String)

显然,注入器正试图找到一个字符串"提供者,但找不到任何.

Clearly, the injector is trying to find a 'string' provider, and can't find any.

我应该使用什么样的模式来处理这种类型的事情?例如.将初始参数传递给组件.

What sort of pattern should I be using for this type of thing? Eg. passing initial parameters to a component.

应该避免吗?我应该注入初始字符串吗?

Should it be avoided? Should I be Injecting the initial string?

推荐答案

您可以使用 @Input() 属性.

<my-component [state]="'joining'"></my-component>

export class AppComponent {
  @Input() state: string;
  constructor() { 
    console.log(this.state) // => undefined
  }
  ngOnInit() {
    console.log(this.state) // => 'joining'
  }
}

构造函数通常只用于 DI...

Constructor should generally be used just for DI...

但如果你真的,真的需要它,你可以创建可注射变量(plunker):

But if you really, really need it you can create injectable variable (plunker):

let REALLY_IMPORTANT_STRING = new OpaqueToken('REALLY_IMPORTANT_STRING');
bootstrap(AppComponent, [provide(REALLY_IMPORTANT_STRING, { useValue: '!' })])

export class AppComponent {
  constructor(@Inject(REALLY_IMPORTANT_STRING) public state: REALLY_IMPORTANT_STRING) { 
    console.log(this.state) // => !
  }
}

最简单的选择是设置类属性:

Simplest option is to just set class property:

export class AppComponent {
  private state:string = 'joining';
  constructor() { 
    console.log(this.state) // => joining
  }
}

正如@Mark 指出的,另一种选择是使用服务:

As @Mark pointed out, another option is to use a service:

export class AppService {
  public state:string = 'joining';
}
export class AppComponent {
  constructor(private service: AppService) { 
    console.log(this.service.state) // => joining
  }
}

这篇关于Angular 2 向构造函数传递参数会引发 DI 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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