Saturday, August 15, 2020

Angular Dependency Injection

Dependency Injection (DI) is a pattern in which a class gets its dependent classes from an external source/framework instead of instantiating them within the class.  Dependency Injection makes an application easy to maintain and makes testing easier, since the dependent objects are injected from outside we can use Mock objects to test the behavior of a class when the actual object is not ready for testing.
 Angular has its own Dependency Injection framework, the common practice in Angular is to inject dependent services to a component using Dependency Injection. The Component takes care of the UI and the injected services takes care of data and validations required by the Component.   

As we saw in the previous post when we create a service to be used in components we need to declare it with the @Injectable() decorator. A provider tells an injector how to create the service. You must configure an injector with a provider before that injector can create a service.

@Injectable({
  providedIn: 'root',
})


The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule. A root provider tells the injection that a singleton version of the service is to be created and shared across all the Components.

To use a service in a component we need to specify the service in the constructor of the Component, this way Angular injects the instance of the dependent service when initializing the component.

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html'
})
export class HelloComponent implements OnInit { 
  constructor(private helloService: HelloService) { }
  . . .
}


Search Flipkart Products:
Flipkart.com

No comments: