我如何让 angular2 依赖注入与值提供者一起工作 [英] how do I get angular2 dependency injection to work with value providers
问题描述
我正在关注依赖注入的角度文档,并试图复制 依赖注入令牌.但很明显我仍然不明白.
I'm following the angular docs for Dependency Injection and tried to duplication the section on dependency injection tokens. But it's clear I still don't get it.
我正在尝试使用 value provider
将 config:any
注入到我的项目中.
I'm trying to use a value provider
to inject an config:any
into my project.
在最简单的层面上,我只想提供
一个常量字符串
At the simplest level, I just want to provide
a const string
// app-modules.ts
const CFG_STRING = "I was declared externally and injected in ngModule"
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
providers: [
{provide: CFG_STRING, useValue: CFG_STRING}
],
bootstrap: [ App ]
})
和注入
到一个组件构造函数中
and inject
into a Component constructor
// app.ts
const LOCAL_STRING = "I was declared in the local module"
export class App {
constructor(
// @Optional() cfgString: CFG_STRING
) {
this.name = 'Angular2'
this.local = LOCAL_STRING
/* provided/injected */
// this.injectedStr = cfgString
}
}
但是当我这样做时,应用程序无法正常运行.我做错了什么?
But when I do so the app doesn't run correctly. What am I doing wrong?
这是一个 plunkr:http://plnkr.co/edit/sQwxyDqLkMTgVUjJ1yYF?p=preview
Here's a plunkr: http://plnkr.co/edit/sQwxyDqLkMTgVUjJ1yYF?p=preview
推荐答案
如果您不使用类型作为提供程序的键,而是使用字符串或 OpaqueToken
您需要将键传递给@Inject()
If you don't use a type as key for the provider but instead a string or OpaqueToken
you need to pass the key to @Inject()
constructor(
@Inject('CFG_STRING') /* @Optional()*/ cfgString: CFG_STRING
) {
并提供它
providers: [
{provide: 'CFG_STRING', useValue: CFG_STRING}
],
CFG_STRING
不是类型,因此不能用作键.要么使用某个字符串,要么提到了 OpaqueToken
.可以是任意字符串,只需要在provide
和@Inject()
CFG_STRING
is not a type and can therefore not be used as key. Either you use some string or mentioned an OpaqueToken
. It can be any string, it just needs to match between provide
and @Inject()
这篇关于我如何让 angular2 依赖注入与值提供者一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!