Getting Started With DI in Angular 2

One of the core features of Angular 2 is dependency injection. This post serves as an introduction to using DI in Angular 2 apps.

Hierarchical DI

Angular 2 uses a hierarchical system for managing injectable objects. For developers this means that the choice of having a new instance or a previously created one is up to the consumer of the injectable. Let’s see how this works. Consider the following example of a single component and a single service (service definition not shown):

<br />
@Component({<br />
    selector: 'parent-component'<br />
    bindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;h1&gt;Hello World&lt;/h1&gt;'<br />
})<br />
class ParentComponent{<br />
    constructor(myUtils: MyUtilsService) {<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}<br />

In the above sample line 3 creates a binding to “MyUtilsService”. This informs Angular that ParentComponent needs a fresh injector to provide access to MyUtilsService. The reference to MyUtilsService on line 9 is the actual request to perform injection. At this point Angular will create a new instance of MyUtilsService which is available in ParentComponent’s constructor. Let’s add another piece.

<br />
@Component({<br />
    selector: 'child-component-1',<br />
})<br />
@View({<br />
    template: '&lt;h2&gt;Child 1 Content&lt;/h2&gt;'<br />
})<br />
class ChildComponent1{<br />
    constructor(myUtils: MyUtilsService) {<br />
        //Same instance of myUtils as injected into ParentComponent<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}</p>
<p>@Component({<br />
    selector: 'parent-component'<br />
    bindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;child-component-1&gt;&lt;/child-component-1&gt;'<br />
    directives: [ChildComponent1]<br />
})<br />
class ParentComponent{<br />
    constructor(myUtils: MyUtilsService) {<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}<br />

In this example ChildComponent1 is also referencing an injection of MyUtilsService. Since a binding was not specified for MyUtilsService on ChildComponent1 Angular injects the same instance that was created for the ParentComponent. But what if we wanted a new instance? Let’s say that ParentComponent manipulates the state of MyUtilsService in some way that makes its use undesirable in some additional child component. To achieve this a new instance would be needed instead of using the parent’s copy.

<br />
//ChildComponent1<br />
@Component({<br />
    ...<br />
})</p>
<p>//ChildComponent2<br />
@Component({<br />
    selector: 'child-component-2'<br />
    bindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;h2&gt;Child 2 Content&lt;/h2&gt;'<br />
})<br />
class ChildComponent2{<br />
    constructor(myUtils: MyUtilsService) {<br />
        //This references a different instance of myUtils from ParentComponent and ChildComponent1<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}<br />
@Component({<br />
    selector: 'parent-component'<br />
    bindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;child-component-1&gt;&lt;/child-component-1&gt;&lt;child-component-2&gt;&lt;/child-component-2&gt;'<br />
    directives: [ChildComponent1, ChildComponent2]<br />
})<br />
class ParentComponent{<br />
    constructor(myUtils: MyUtilsService) {<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}<br />

Now a new instance of the MyUtilsService is requested on line 9 by creating a child injector. As a result, ChildComponent2’s constructor will be supplied with a different instance than was injected into the ParentComponent. Lets add one more layer and assume that ChildComponent2 is the only component in this hierarchy in need of a separate instance of MyUtilsService. ChildComponent2’s child wants to inject the same instance that was created for and injected into ParentComponent. One may assume the following approach can be taken:

<br />
//ChildComponent1<br />
@Component({<br />
    ...<br />
})</p>
<p>//ChildComponent2<br />
@Component({<br />
    selector: 'child-component-2'<br />
    bindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;grandchild-component&gt;&lt;/grandchild-component&gt;'<br />
    directives: [GrandchildComponent]<br />
}</p>
<p>//GrandchildComponent<br />
@Component({<br />
    selector: 'grandchild-component'<br />
    bindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;h3&gt;Grandchild Content&lt;/h3&gt;'<br />
})<br />
class GrandchildComponent{<br />
    constructor(myUtils: MyUtilsService) {<br />
        //This will look for and find the instance of MyUtilsService created by ChildComponent2<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}</p>
<p>//ParentComponent<br />
@Component({<br />
    ...<br />
}<br />

However, the GrandChildComponent is receiving a third instance of MyUtilsService. This is also not ideal. To correct this and achieve the desired result let’s revisit ChildComponent2 and make a few small adjustments.

<br />
//ChildComponent1<br />
@Component({<br />
    ...<br />
})</p>
<p>//ChildComponent2<br />
@Component({<br />
    selector: 'child-component-2'<br />
    viewBindings: [MyUtilsService]<br />
})<br />
@View({<br />
    template: '&lt;grandchild-component&gt;&lt;/grandchild-component&gt;'<br />
    directives: [GrandchildComponent]<br />
}</p>
<p>//GrandchildComponent<br />
@Component({<br />
    selector: 'grandchild-component'<br />
})<br />
@View({<br />
    template: '&lt;h3&gt;Grandchild Content&lt;/h3&gt;'<br />
})<br />
class GrandchildComponent{<br />
    constructor(myUtils: MyUtilsService) {<br />
        //This will look for and find the instance of MyUtilsService created by ChildComponent2<br />
        console.log(myUtils.getMessage());<br />
    }<br />
}</p>
<p>//ParentComponent<br />
@Component({<br />
    ...<br />
}<br />

View bindings allow for the creation of injectors that will create instances of an injectable that are only available to the component they are declared on. When MyUtilsService is injected into the GrandchildComponent the DI system will climb the hierarchy looking for an injector that is aware of MyUtilsService. The instance created by ChildComponent2 is not present in the hierarchy and instead the instance created on the ParentComponent is used.

App Level Instances

In addition to creating dependency bindings at the component level it is also possible to specify a set of top level, application dependencies. This is done using the bootstrap function to initialize the application. For example:

<br />
bootstrap(ParentComponent, [MyUtilsService])<br />

Now any component of the application can inject the same instance of MyUtilsService or request a new copy using the binding approaches listed above.

Conclusion

There is great flexibility and power in the new dependency system. This article covers some of the basics that can be used to get your application off the ground but there is still plenty more to learn about how it works under the hood. For more information about how the Angular 2 dependency injection system works check out one of the following resources:
http://victorsavkin.com/post/102965317996/angular-2-bits-unified-dependency-injection
https://angular.io/docs/js/latest/api/di/