如何使用依赖注入(DI)正确Angular2? [英] How to use Dependency Injection (DI) correctly in Angular2?

查看:389
本文介绍了如何使用依赖注入(DI)正确Angular2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找出在Angular2如何(DI)的依赖注入工作。我每次碰到了很多问题/问题,当我试图注入服务/或类到我的部件。

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.

从不同一派文章中,我需要或者使用供应商:[]在组件配置,有时我需要在我的构造函数中使用@Inject()或直接在引导注入(应用程序,[服务])?我也看到了一些文章要我把@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,我只需要输入{}的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.

有没有时使用何种拇指任何规则?能否请您提供一些例如code段?谢谢: - )

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:


    自举时,它
  • 对于整个​​应用程序。在这种情况下,所有子喷射器(组件的)将会看到这个供应商并分享相关的实例。交互时,这将是相同的实例

  • 对于一个特定的组件及其子组件。与以前一样,但对于特定的组件。其他组件将不会看到这个供应商。如果上面的重新定义(如自举时)定义的东西,这个供应商将被用来代替。所以,你可以忽略的东西。

  • 有关服务。没有与他们有联系的供应商。他们使用从触发元素注入的那些(直接=组件或间接=触发服务链的调用组件)

关于你提到的其他问题:

Regarding your other questions:


  • @Injectable。要注入的一类,你需要一个装饰。组件有一个(@Component一个),但服务是简单的类。如果一个服务需要依赖它被注入,则需要这个装饰。

  • @Inject。在大多数时候,的构造函数的参数类型是足以让Amgular2确定注入什么。在某些情况下(例如,如果您明确使用OpaqueToken而不是类注册供应商),你需要指定什么注入一些提示。在这种情况下,你需要使用@注入。

请参阅这些问题的更多详细信息:

See these questions for additional details:

  • What's the best way to inject one service into another in angular 2 (Beta)?
  • Angular2: Inject a non @Injectable class
  • Inject all Services that implement some Interface

这篇关于如何使用依赖注入(DI)正确Angular2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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