Saturday, June 11, 2016

Angular2 JS - Dependency Injection

So far we created components, added services. For us to understand few other tricks in dependency injection, though subtle, we may have to start from first. Let's create a new application from seed, and add couple of components. This exercise will also help you get you familiar with component creation process.

app.component.ts
/**
 * Created by krishnansriramrama on 6/1/16.
 */
import {Component} from 'angular2/core';
import {Component1Component} from "./component1.component";
import {Component2Component} from "./component2.component";

@Component({
    selector: 'my-app',
    template: `
        <div class="row">
            <div class="col-md-6">
                <my-component1></my-component1>
            </div>
            <div class="col-md-6">
                <my-component2></my-component2>
            </div>
        </div>
    `,
    directives: [Component1Component, Component2Component]
})
export class AppComponent {

}


Add 2 components, pretty simple one's. They add new items into array. Our exercise is to see if items we add in one component, reflects on the other. If we add services to component through "dataProviders", which I encourage you to try by yourself, you'll notice that items added in one component, does not show up in the other. If you wonder why? It's because, Angular2 creates 2 different instances of service object and shares it with components. That explains to why we data was not shared. What's the other approach you as. Keep following

component1.component.ts 

/**
 * Created by krishnansriramrama on 6/1/16.
 */
import {Component, ElementRef, OnInit} from 'angular2/core';
import {DataService} from "./data.service";

@Component({
    selector: 'my-component1',
    template: `
        <div class="panel panel-default">
            <div class="panel-heading"><h1>Component 1</h1></div>
            <div class="panel-body">
                <button (click)="onGetData()">Get random data</button>
                <p>Random data: {{data}}</p>
                <input type="text" #input>
                <button (click)="onAddItem(input.value)">Add</button>
            </div>
        </div>
    `,
})
export class Component1Component {
    data:string;

    constructor(private _dataService:DataService){}

    onGetData() {
        this.data = this._dataService.getRandomData();
    }
    
    onAddItem(data:string) {
        this._dataService.insertData(data);
    }
    
}

component2.component.ts 

/**
 * Created by krishnansriramrama on 6/1/16.
 */
import {Component} from 'angular2/core';
import {DataService} from "./data.service";

@Component({
    selector: 'my-component2',
    template: `
        <div class="panel panel-default">
            <div class="panel-heading"><h1>Component 1</h1></div>
            <div class="panel-body">
                <button (click)="onGetData()">Get random data</button>
                <p>Random data: {{data}}</p>
                <input type="text" #input>
                <button (click)="onAddItem(input.value)">Add</button>
            </div>
        </div>
    `,
})
export class Component2Component {
    data:string;

    constructor(private _dataService:DataService){}

    onGetData() {
        this.data = this._dataService.getRandomData();
    }

    onAddItem(data:string) {
        this._dataService.insertData(data);
    }
}

data.service.ts 


/**
 * Created by krishnansriramrama on 6/1/16.
 */
export class DataService {
    private _data = ['Milk', 'Brown Sugar', 'Bagel'];

    getRandomData() {
        return this._data[Math.floor(Math.random() * this._data.length)];
    }

    insertData(data: string) {
        this._data.push(data);
    }
}

For data service to be available to both components, we add it to boot.ts. Updated boot.ts looks like the following

boot.ts 
 
///
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./app.component";
import {DataService} from "./data.service";

bootstrap(AppComponent, [DataService]);

Run the app, you'll see data is shared amongst components. Hope that gives some context on dependency injection in Angular2 

No comments:

Post a Comment