Angular 2.0 – Dependency Injection

Dependency Injection is a way to provide a dependency or in more simple terms provides an instance of a class which is required.

Services are the most common dependencies. Services are injected in the component through its constructor and thereby consumed by the Component.

How the whole process works

Injector is the main mechanism. Injector maintains a container of service instances. When Angular creates a component, it asks injector if the service instance is available in its container. If it is not then the injector creates one and add it to its container before returning to Angular.

All the requested services are resolved means their instances are put into the injector’s container and are returned. Then Angular call the Component’s constructor and inject the appropriate service according the parameters provided.

Dependency Injection

How does an injector knows that a new service instance is required

For that we have to Register Providers with Injectors.
Providers create and return instance of services.

You have seen them in module class and in component class.
Generally, we add providers in the root module so that same instance of the service can be used in the whole application.
We can also register providers in the Component , we have providers property in the @Component metadata.

app/app.module.ts

providers: [
LoggingService,
UserService,
],

app/user.component.ts

@Component({
selector: ‘user-name’,
templateUrl: ‘./user.component.html’,
providers: [ UsersService ]
})