angularangular2-servicesangular2-di

How to use Dependency Injection (DI) correctly in 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.

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.

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 :-)


Solution

  • 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:

    See these questions for additional details: