如何在 Angular2 中正确使用依赖注入(DI)? [英] How to use Dependency Injection (DI) correctly in Angular2?
问题描述
我一直试图弄清楚 (DI) 依赖注入在 Angular2 中是如何工作的.每次尝试将服务/或类注入到我的组件中时,我都会遇到很多问题/问题.
I have been trying to figure out how the (DI) Dependency Injection work in Angular2. I ran into lots of problem/issue every time when I tried to Inject a service/or class into my components.
从不同的谷歌搜索文章中,我需要在组件配置中使用 providers: []
,或者有时我需要在构造函数中使用 @Inject()
或直接注入bootstrap(app, [service])
?我也看到一些文章要我放 @injectable
装饰器.
From different googled articles, I need to either use providers: []
in the Component configuration, or sometimes I need to use @Inject()
in my constructor or inject directly in the bootstrap(app, [service])
? I've also seen some articles want me to put @injectable
decorator.
例如:要注入Http,我只需要import{Http}
并将Http放入提供者中,但是对于FormBuilder,我需要使用@Inject()
在构造函数中.
For example: to inject Http, I only need to import{Http}
and put Http in the providers, but for FormBuilder, I need to use @Inject()
in constructor.
对于何时使用什么有什么经验法则吗?你能提供一些示例代码片段吗?谢谢:-)
Is there any rule of thumb for when to use what? Could you please provide some example code snippet? Thank you :-)
推荐答案
Angular2 中的依赖注入依赖于链接到组件树的分层注入器.
Dependency injection in Angular2 relies on hierarchical injectors that are linked to the tree of components.
这意味着您可以在不同级别配置提供程序:
This means that you can configure providers at different levels:
- 在引导整个应用程序时.在这种情况下,所有子注入器(组件注入器)都会看到这个提供者并共享与之关联的实例.交互时,会是同一个实例
- 针对特定组件及其子组件.与之前相同,但针对特定组件.其他组件将看不到此提供程序.如果您重新定义上面定义的内容(例如在引导时),则将使用此提供程序.所以你可以覆盖一些东西.
- 用于服务.没有与它们关联的提供程序.他们使用来自触发元素的注入器(直接=组件或间接=触发服务链调用的组件)
关于您的其他问题:
- @Injectable.要注入一个类,你需要一个装饰器.组件有一个(@Component 一个),但服务是简单的类.如果服务需要在其中注入依赖项,则需要此装饰器.
- @Inject.大多数时候,构造函数参数的类型足以让Angular2决定注入什么.在某些情况下(例如,如果您显式使用 OpaqueToken 而不是类来注册提供程序),您需要指定一些有关注入内容的提示.在这种情况下,您需要使用@Inject.
有关其他详细信息,请参阅这些问题:
See these questions for additional details:
这篇关于如何在 Angular2 中正确使用依赖注入(DI)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!