Dependency Injection in Angular

Dependency Injection

Dependency injection is a significant application design pattern suggested by Angular. Angular has its own design DI framework to make Angular applications modular. The DI framework gives declared dependencies to a class when the class is instantiated. In DI design pattern, a class requires dependencies from external sources rather than creating by itself.

What are dependencies?
Dependencies are services or objects that a class needs to perform its tasks. A dependency doesn't have to be a service, it could be a function or a value.

Services and Dependency Injection

A service is a class for a particular dedicated purpose. In Angular, components and services are used to increase modularity and reusability. Using services, components will assign specific tasks to services such as fetching data from the server and validating user input. In Angular, we define processing tasks in an injectable service class. Using injectable decorator, these services will be available to any component. We can inject different providers for the same service as required to make our Angular project. Services are available to components through dependency injection. Dependency injection injects services in the constructor of the components.

Service examples

Here is an example of a service called ContactService that fetch all the contacts data from the server.
Services can depend on other services. Like in our example below our service depends on HttpClient service to fetch the data from the server.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ContactService {
  constructor(private http: HttpClient) {
    this.contacts = new Array<ContactModel>();
  }

  public getAllContacts(): Promise {
    return this.http.get(URL).toPromise()
      .then((res: any) => {
        return res.data;;
      });
  }

Defining a service

To define a class as a service in Angular, @Injectable decorator is used to provide the metadata that allows Angular to inject it into a component as a dependency. 
  • The injector is the main working process. Angular creates an injector which is used across the application during the bootstrap process.
  • We don't have to create injectors in Angular.
  •  An injector creates dependencies and maintains dependency instances for reuse overtime.
  • A provider is an object that conveys an injector how to get a dependency. 
When Angular creates an instance of the component class, it determines which dependencies are required by the component by checking the constructor parameter types. The following code is required to inject a service in the component's constructor.

constructor(private _contactService: ContactService) { }

Comments