{"id":37767,"date":"2016-07-30T14:49:42","date_gmt":"2016-07-30T09:19:42","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=37767"},"modified":"2017-09-12T12:43:23","modified_gmt":"2017-09-12T07:13:23","slug":"angular-2-dependency-injection-2","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/angular-2-dependency-injection-2\/","title":{"rendered":"Angular 2 Dependency Injection"},"content":{"rendered":"<p style=\"text-align: justify;\"><span style=\"font-weight: 400;\">In this blog, we will go through the new dependency injection system of <a title=\"Angular 2 Development\" href=\"http:\/\/www.tothenew.com\/front-end-angularjs-development\">Angular 2<\/a>. As we know\u00a0<\/span>DI is the heart of AngularJS. In Angular 1 we can inject dependency at multiple places in different ways such as:<\/p>\n<ul>\n<li>in the directive definition by name \u00a0\u00a0eg.\n<p>[js]app.directive(&#8216;questionTemplate&#8217;, [&#8216;$http&#8217;, &#8216;Flash&#8217;, function($http, Flash) {}[\/js]<\/p>\n<\/li>\n<li>in the controller function by name, etc. eg.\n<p>[js]app.controller(\u2018myController\u2019,[\u201c$scope\u201d,function($scope){}])[\/js]<\/p>\n<\/li>\n<\/ul>\n<p><strong><span style=\"font-weight: 400;\">In Angular 2 there is only one way of injecting DI i.e Constructor injection by type,<\/span><\/strong><\/p>\n<p>[js]<br \/>\nconstructor(dateUtil: DateUtil){<br \/>\n\tthis.dateUtil = dateUtil<br \/>\n}<\/p>\n<p>class DateUtil{<br \/>\n\tdate:Date<\/p>\n<p>\tconstructor(date: string) {<br \/>\n\t\tthis.date = new Date(string);<br \/>\n\t}<\/p>\n<p>\tgetDate() {<br \/>\n\t\treturn this.date;<br \/>\n\t}<br \/>\n}[\/js]<\/p>\n<p>In the above example, it tells the constructor that class depends on \u201cDateUtil\u201d which in our case is a\u00a0 utility wrapper for dealing with dates.Let&#8217;s start with \u00a0the concept of DI in Angular 2. The DI system in Angular 2 basically consists of three important aspects:<\/p>\n<p style=\"text-align: justify;\"><b><span style=\"text-decoration: underline;\">Injector<\/span>:<\/b><span style=\"font-weight: 400;\"><br \/>\nThe injector object provides us a mechanism by which the desired dependency is instantiated.To\u00a0<\/span><strong><span style=\"font-weight: 400;\">create an instance ,injector looks for a provider.<\/span><\/strong><\/p>\n<p style=\"text-align: justify;\"><strong><span style=\"text-decoration: underline;\"><b>Provider<\/b><\/span><span style=\"font-weight: 400;\">:<\/span><\/strong><br \/>\nA Provider is a medium by which we register our dependency that need to be inject.\u00a0As with all DI frameworks, we have to inform them about the dependencies that we want to inject \u201csomewhere\u201d. The way we do this in Angular 2.0 is by specifying \u201cproviders\u201d . This\u00a0can be done in 2 ways<\/p>\n<ul>\n<li style=\"text-align: justify;\">Registering the provider at the app level creates the injected dependency as a singleton \u00a0for the entire application eg.\n<p>[js]bootstrap(App, [NameService]);[\/js]<\/p>\n<\/li>\n<li>Providers at the component level result in new instances at the component level eg.\n<p>[js]@Component({providers: [NameService]})[\/js]<\/p>\n<\/li>\n<\/ul>\n<p style=\"text-align: justify;\">This is the difference in Angular 1 DI where we have only singleton dependency for the whole\u00a0application.<\/p>\n<p style=\"text-align: justify;\"><strong><span style=\"text-decoration: underline;\"><b>Dependency<\/b><\/span><\/strong><br \/>\nThe dependency that we are injecting in a constructor is an object\u00a0<span style=\"line-height: 1.71429; font-size: 1rem;\">of the class that\u00a0<\/span><span style=\"font-weight: 400;\">we want to use eg. \u00a0\u00a0<\/span><span style=\"font-weight: 400;\">dateUtil:DateUtil\u00a0<\/span><\/p>\n<p style=\"text-align: justify;\">Let&#8217;s suppose we have a class car which depends on Engine and Tire dependency<\/p>\n<p>[js]<br \/>\nclass Car{<br \/>\n\tconstructor ( engine, tires ) {<br \/>\n\t\tthis.engine = engine;<br \/>\n\t\tthis.tires = tires;<br \/>\n\t}<br \/>\n}[\/js]<\/p>\n<p style=\"text-align: justify;\"><strong><span style=\"font-weight: 400;\">Here\u2019s how we can use Angular 2\u2019s DI to get an instance of Car:<\/span><\/strong><\/p>\n<p>[js]<br \/>\nimport { ReflectiveInjector } from &#8216;@angular\/core&#8217;;<\/p>\n<p>var injector = ReflectiveInjector.resolveAndCreate([ Car, Engine, Tires ]);<br \/>\nvar car = injector.get(Car);<br \/>\n[\/js]<\/p>\n<p><strong><b>How the injector works:<\/b><\/strong><\/p>\n<p>ReflectiveInjector is an injector implementation that gives resolveAndCreate() factory function that creates an injector object and takes a list of providers. How does injector know which dependencies need to be created in order to instantiate a car? In order to specify this, we simply\u00a0use these objects in the Car constructor(engine, tires) \u00a0but we do not mention any dependencies about these classes yet.<\/p>\n<p>[js]<br \/>\nimport { Inject } from &#8216;angular2\/core&#8217;;<\/p>\n<p>class Car{<br \/>\n\tconstructor ( @Inject(Engine) engine, @Inject(Tires tire{&#8230;})<br \/>\n}<br \/>\n[\/js]<\/p>\n<p style=\"text-align: justify;\">We import \u00a0Inject from the framework.The Inject decorator<span style=\"font-weight: 400;\"> \u00a0attaches metadata to our Car\u00a0<\/span>class, which is used by the DI system later. So basically what we\u2019re doing here, is that we tell the DI that the first constructor parameter should be an instance of type Engine, the second of type\u00a0<strong><span style=\"font-weight: 400;\"><strong><span style=\"font-weight: 400;\">Tires.So we can rewrite our code in typescript-<\/span><\/strong><\/span><\/strong><\/p>\n<p>[js]<br \/>\nclass Car {<br \/>\n\tconstructor ( engine: Engine, tires: Tires ) {<br \/>\n        &#8230;<br \/>\n    }<br \/>\n}<br \/>\n[\/js]<\/p>\n<h4><strong><b>How a provider works:<\/b><\/strong><\/h4>\n<p style=\"text-align: justify;\"><span style=\"font-weight: 400;\">Still, injector does not know about the classes?.i.e we just provide a token<\/span><span style=\"font-weight: 400;\">\u00a0of dependency but\u00a0<\/span>nothing about their classes like Engine, Tires.This is where the providers come into the picture.Let&#8217;s have a look how it goes-<\/p>\n<p>[js]<br \/>\nimport { provide } from &#8216;angular2\/core&#8217;;<\/p>\n<p>var injector = RelfectiveInjector.resolveAndCreate([<br \/>\n\tprovide(Car, { useClass: Car }),<br \/>\n\tprovide(Engine, { useClass:Engine }),<br \/>\n\tprovide(Tires, { useClass:Tires })<br \/>\n]);[\/js]<\/p>\n<p style=\"text-align: justify;\"><span style=\"font-weight: 400;\">We have a function provide() that maps a\u00a0<\/span>token<span style=\"font-weight: 400;\"> to a configuration object.We provide an\u00a0<\/span>instance of type Car via the class Car, type Engine via the class Engine and so on and so forth.So with the providers &#8211;<\/p>\n<ol>\n<li>We let the injector know which dependencies are used across the application i.e at the component level\u00a0or app level as we talked earlier in above.<\/li>\n<li>We also configure how objects of these dependencies are created i.e which implementation used with the object.For example-<\/li>\n<\/ol>\n<p>[js]<br \/>\nprovide(Engine, {<br \/>\n    useClass: OtherEngine<br \/>\n})<br \/>\n[\/js]<\/p>\n<p style=\"text-align: justify;\">We will use this syntax where we need to use a dependency with a different implementation.This\u00a0is the powerful feature, about which we already talked in above i.e use same type dependency with different implementations.How it works in Angular 2-<\/p>\n<p>Let&#8217;s take a look at a complete example, creating a <a title=\"Angular 2 Component\" href=\"http:\/\/www.tothenew.com\/blog\/building-intuitive-frontend-interfaces-with-angularjs\/\">simple Angular 2 component<\/a> &#8211; which uses DI to inject dependencies:<\/p>\n<p>[js]<br \/>\n@Component({<br \/>\n    selector: &#8216;app&#8217;,<br \/>\n    template: &#8216;&amp;lt;h1&amp;gt;Hello !&amp;lt;\/h1&amp;gt;&#8217;<br \/>\n})<\/p>\n<p>class App {<br \/>\n    constructor (@Inject(NameService) NameService){<br \/>\n        this.name = NameService.getName();<br \/>\n    }<br \/>\n}<\/p>\n<p>class NameService {<br \/>\n    constructor () {<br \/>\n        this.name = &#8216;Pascal&#8217;;<br \/>\n    }<br \/>\n    getName () {<br \/>\n        return this.name;<br \/>\n    }<br \/>\n}<\/p>\n<p>bootstrap(App, [NameService]);[\/js]<\/p>\n<p style=\"text-align: justify;\"><span style=\"font-weight: 400;\">bootstrap() takes care of creating a root injector for our application when it\u2019s bootstrapped. It\u00a0<\/span>takes a list of providers as the second argument which will be passed straight to the injector when it is created<span style=\"line-height: 1.71429; font-size: 1rem;\">.<\/span>So I \u00a0hope you got the concept behind DI in Angular 2 &amp; its working.<\/p>\n<p><span style=\"font-size: 20px; color: blue;\">Read Further on AngularJS Series<\/span><\/p>\n<ul>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-a-write-less-do-more-javascript-framework\/\">AngularJS :\u00a0A \u201cWrite Less Do More\u201d JavaScript Framework<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-updating-a-label-dynamically-with-user-input\/\">AngularJS :\u00a0Updating a Label Dynamically with User Input<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-adding-items-to-a-javascript-list-and-updating-corresponding-dom-dynamically\/\">AngularJS :\u00a0Adding Items to a JavaScript List and updating corresponding DOM Dynamically<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-text-suggestions\/\">AngularJS :\u00a0Text Suggestions<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-sorting-objects-on-various-attributes\/\">AngularJS :\u00a0Sorting objects on various attributes<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-fetching-data-from-the-server\/\">AngularJS :\u00a0Fetching data from the server<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-multiple-views-layout-template-and-routing\/\">AngularJS :\u00a0Multiple Views, Layout\u00a0Template\u00a0and Routing<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-implementing-routes-and-multiple-views\/\">AngularJS :\u00a0Implementing Routes And Multiple Views<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/building-intuitive-frontend-interfaces-with-angularjs\/\">Building Intuitive Frontend Interfaces with AngularJS<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In this blog, we will go through the new dependency injection system of Angular 2. As we know\u00a0DI is the heart of AngularJS. In Angular 1 we can inject dependency at multiple places in different ways such as: in the directive definition by name \u00a0\u00a0eg. [js]app.directive(&#8216;questionTemplate&#8217;, [&#8216;$http&#8217;, &#8216;Flash&#8217;, function($http, Flash) {}[\/js] in the controller function [&hellip;]<\/p>\n","protected":false},"author":441,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":1},"categories":[1439,3429,1],"tags":[3858,3955,3856,4697,1865,3857,1450],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/37767"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/441"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=37767"}],"version-history":[{"count":1,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/37767\/revisions"}],"predecessor-version":[{"id":51793,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/37767\/revisions\/51793"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=37767"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=37767"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=37767"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}