Injector, Injectable And Inject In Angular

Injector, Injectable And Inject In Angular

The Angular Injector is the brains behind the Angular Dependency Injection architecture. In this article we will discuss in more details. The @Injectable and @Inject decorators will also be examined.

What is Angular Injector

The Angular Injector is in charge of instantiating and injecting dependencies into components and services.

Using the Injection token, the Injector searches the Angular Providers for the dependency. The Provider, which holds information on how to construct an instance of the dependent, is returned by the Angular Providers array. The Injector is responsible for creating the instance and injecting it into the Component or Service.

When is Angular Injector is created

When the application bootstraps, Angular generates two injector trees. The ElementInjector tree is for Elements, while the ModuleInjector tree is for Modules (Components & Directives etc).

When the application bootstraps, Angular loads the Root Module (AppModule). For the Root Module, it makes RootModule Injector. The application-wide reach of this injector is impressive. The ModuleInjector Tree gains the RootModule Injector as a child.

The AppComponent, the root component of our project, is loaded by Angular Root Module. The AppComponent is provided with its own injector. Injector is the name we give to this root. The root of the ElementInjector tree becomes this Injector.

All additional components are contained in the Root Component. Under the Root Component, Angular App will build child components. All of these kid components can have their own children, forming a component tree. In addition, Angular constructs an Injector for each of those components, resulting in an Injector tree that roughly resembles the component tree. The ElementInjector tree now contains these Injectors.

Registering the service with injector

All of the application's dependencies are registered with the Providers. A Provider is associated with each injector. We register our reliance in the Providers metadata of @NgModule@Component, or @Directive.

providers: [ProductService, LoggerService]

The scope of a dependency is determined by where it is registered. The Root Provider is attached to the dependency registered with the Module using the @NgModule decorator ( Provider attached to the Root Injector). The entire application has access to this dependency.

The dependency that is registered with the component is available to that component as well as any of its descendant components.

The ProvidedIn property of the Injectable decorator is another approach to declare dependencies.

@Injectable

The Injectable is a decorator that must be added to the dependency's consumer. This decorator instructs Angular to use the Angular DI system to inject the constructor arguments.

Example of Injectable

In the Angular Dependency Injection lesson, we built an example application. As indicated below, it had two services: LoggerService and ProductService.

LoggerService
import { Injectable } from '@angular/core';
 
import { Injectable } from '@angular/core';
 
@Injectable()
export class LoggerService {
  log(message:any) {
    console.log(message);
  }
}

ProductService
import { Injectable } from '@angular/core';
 
import {Product} from './Product'
import {LoggerService} from './logger.service'
 
@Injectable()
export class ProductService{
 
    constructor(private loggerService: LoggerService) {
        this.loggerService.log("Product Service Constructed");
    }
 
    public  getProducts() {
 
        this.loggerService.log("getProducts called");
        let products:Product[];
 
        products=[
            new Product(1,'Memory Card',500),
            new Product(1,'Pen Drive',750),
            new Product(1,'Power Bank',100)
        ]
 
        this.loggerService.log(products);
        return products;               
    }
}

The LoggerService is a requirement for the ProductService. As a result, the @Injectable decorator is applied. You will get the following error if you remove @Injectable() from ProductService.

That's because Angular won't be able to inject LoggerService into ProductService without DI.

There will be no issue if you remove @Injectable() from LoggerService because it has no dependencies.

The @Component and @Directive decorators have previously been applied to the Components and Directives. You don't need to add the @Injectable() decorator because these decorators already tell Angular to use DI.

The ProvidedIn property of the injectable decorator allows you to specify how Angular should provide the dependency.
@Injectable({  
   providedIn: 'root'
})
export class SomeService{
}

@Inject

@Inject() is a constructor parameter decorator that instructs angular to inject the parameter with the dependency specified in the token. It's a time-consuming method of injecting the dependency.

When we removed the @Injectable decorator from the ProductService in the previous example, we got an error.

The LoggerService can be manually injected by applying the @Inject decorator to the parameter loggerService, as seen below.

The Injector token is passed as a parameter to @Inject. The dependence is located in the Providers using the token.
export class ProductService{
    constructor(@Inject(LoggerService) private loggerService) {
        this.loggerService.log("Product Service Constructed");
    }
}

Conclusion

In this article, We learned @Injectable and @Inject in more details. The Angular Injector is the brains behind the Angular Dependency Injection architecture.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post