Angular 2 向构造函数传递参数会引发 DI 异常

编程入门 行业动态 更新时间:2024-10-27 23:29:44
本文介绍了Angular 2 向构造函数传递参数会引发 DI 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 23:03:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1031303.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   异常   参数   Angular   DI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!