How to use Dependency Injection (DI) correctly in Angular2?

Viewed 19631

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

5 Answers
Related