- We have a fundamental problem with our design, which dependency injection can help us fix.Using Dependency InjectionWe can solve our problem by injecting an instance of LoginService into the constructor instead of creating it directly.Now, we need to tell the framework how to create an instance of the service.All right, letâs port this example to Angular 2.
- In Angular 2 we can do it by adding the service to the list of providers.NgModule is the âdefaultâ place to configure dependency injection providers.
- In this example a single instance of the login service will be created, and it will available for the login component and any of its descendants.Scoping DI to a Component SubtreeDependency injection in Angular 2 is more flexible.
- The way it works is as follows:The framework builds a tree of injectors that matches the DOM.tabpane title=âoneâ/panepane title=âtwoâ/pane/tabThe matching injector tree:Injector matching tab | |__Injector matching pane title=âoneâ | |__Injector matching pane title=âtwoâSince there is an injector for every DOM element, the framework can provide contextual or local information, such as an element, attributes, or nearby directives.This is how the dependency resolution algorithm works.So if Pane depends on Tab, Angular will start by checking if the pane element happens to have an instance of Tab.
- In Angular 2, where every element has an injector, this is not a problem.The services and directives created under SubApp1 will use CustomPaymentService1, and the ones created under SubApp2 will use CustomPaymentService2, even though all of them declare a dependency on injection is one of the core parts of Angular 2.
Which developers do you think would benefit most from this? Dependency Injection in Angular 1 and Angular 2 > https://t.co/zLqeunpcIA
— AngularJS News (@AngularJS_News) August 2, 2017