Powered by Blogger.

Graphic Works

Category 2

Category 3

Angular 2 - Dependency Injection


Description

Dependency Injection is a design pattern that passes an object as dependencies in different components across the application. It creates a new instance of class along with its required dependencies. The Dependency Injection is stimulated into the framework and can be used everywhere.
You must remember the below points while using Dependency Injection:
  • The injector mechanism maintains service instance and can be created using a provider.
  • The provider is a way of creating a service.
  • You can register the providers along with injectors.

Example

The below example describes use of dependency injection in the Angular 2:
<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 Dependency Injection</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('/angular2/src/app/dependency_injection_main')
            .then(null, console.error.bind(console));
    </script>
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>
The above code includes the following configuration options:
  • You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option.
  • If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser.
  • The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime.
  • Angular 2 includes the packages form the app folder where files will have the .ts extension.
  • Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console.
  • When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags.
Let's create the TypeScript(.ts) files and save them in the app folder.
dependency_injection_main.ts
import {bootstrap} from 'angular2/platform/browser';     //importing bootstrap function
import {AppComponent} from "./fruit-component";          //importing component function

bootstrap(AppComponent);
fruit-component.ts
import {Component} from 'angular2/core';
import {MyListComponent}  from './play-component';

//@Component is a decorator that uses configuration object to create the component and its view.
@Component({
  selector: 'my-app',   //The selector creates an instance of the component where it finds 'my-app' tag in parent HTML
  template:`<my-list></my-list>`,
  directives:[MyListComponent]  //'MyListComponent' is the root component of fruits that governs child components
})
export class AppComponent { }
play-component.ts
import {Component} from "angular2/core";
import {FruitService} from "./fruits.service";
import {Fruits} from "./fruits";
import {OnInit} from "angular2/core";

@Component({
   selector: "my-list",
   template: ` List of Fruits<br>
   <ul>
      <li *ngFor="#list of fruits">  //The NgFor directive instantiates a template once per item from an iterable
         {{list.id}} - {{ list.name }}
      </li>
   </ul>
   `,
   providers: [FruitService]  //providers are part of @Component metadata
})

//The 'MyListComponent' should get list of fruits from the injected 'FruitService'
export class MyListComponent implements OnInit {
   public fruits : Country[];

   //Using constructor, call the _fruitService and populate the fruits list
   constructor(private _fruitService: FruitService) {}

   getContacts(){
      this._fruitService.getContacts().then((fruits: Country[]) => this.fruits = fruits);
   }

   //The 'ngOnInit()' hook is called when done with creating the component and evaluated the inputs
   ngOnInit():any{
      this.getContacts();
   }
}
fruits.service.ts
import {Injectable} from "angular2/core";
import {COUNTRIES} from "./fruits.lists";

//It is used for meta data generation and specifies that class is available to an injector for instantiation
@Injectable()

//'FruitService' exposes 'getContacts()' method that returns list of data
export class FruitService {
   getContacts() {
      return Promise.resolve(COUNTRIES); // takes values from fruits.lists.ts file
   }
}
fruits.lists.ts
import {Fruits} from "./fruits";

//storing array of data in Fruits
export const COUNTRIES: Fruits[] =[
   {"id": 1, name :"Apple"},
   {"id": 2, name: "Grapes"},
   {"id": 3, name: "Orange"},
   {"id": 4, name: "Banana"}
];
fruits.ts
export interface Fruits{
   id: number;
   name: string;
}

Output

Let's carry out the following steps to see how above code works:
  • Save above HTML code as index.html file as how we created inenvironment chapter and use the above app folder which contains .tsfiles.
  • Open the terminal window and enter the below command:
    npm start
  • After few moments, a browser tab should open and displays the output as shown below.
OR you can run this file in another way:
  • Save above HTML code as angular2_dependency_injection.htmlfile in your server root folder.
  • Open this HTML file as http://localhost/angular2_dependency_injection.html and output as below gets displayed.



Angular 2 - Directives


Description

Services are JavaScript functions that are responsible for doing a specific task only. Angular services are injected using Dependency Injection mechanism and include the value, function or feature which is required by the application. There nothing much about service in Angular and there is no ServiceBase class, but still services can be treated as fundamental to Angular application.

Example

The below example describes use of services in the Angular 2:
<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 Services</title>
    <!--Load libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',

        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('/angular2/src/app/service_main')
            .then(null, console.error.bind(console));
    </script>
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>
The above code includes the following configuration options:
  • You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option.
  • If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser.
  • The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime.
  • Angular 2 includes the packages form the app folder where files will have the .ts extension.
  • Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console.
  • When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags.
To run the code, you need the following TypeScript(.ts) files which you need to save under the app folder.
metadata_main.ts
import {bootstrap} from 'angular2/platform/browser';     //importing bootstrap function
import {AppComponent} from "./app_service.component";    //importing component function

bootstrap(AppComponent);
Now we will create a component in TypeScript(.ts) file which we will create a view for the component.
app_service.component.ts
import {Component} from 'angular2/core';
import {MyListComponent} from "./service-list.component";

@Component({
    selector: 'my-app',
    template: `
    <country-list></country-list>
    `,
    directives: [MyListComponent]
})
export class AppComponent {
}
  • The @Component is a decorator which uses configuration object to create the component and its view.
  • The selector creates an instance of the component where it finds <my-app> tag in parent HTML.
  • Next we create a directive called MyListComponent which will be accessed from the service-list.component file.
service-list.component.ts
import {Component} from "angular2/core";
import {CountryService} from "./country.service";
import {Contact} from "./country";
import {OnInit} from "angular2/core";

@Component({
   selector: "country-list",
   template: ` List of Countries<br>
   <ul>
      <li *ngFor="#cntry of countries">{{ cntry.name }}</li>
   </ul>
   `,
   providers: [CountryService]
})

export class MyListComponent implements OnInit {
   public countries : Country[];
   constructor(private _countryService: CountryService) {}

   getContacts(){
      this._countryService.getContacts().then((countries: Country[]) => this.countries = countries);
   }

ngOnInit():any{
   this.getContacts();
}
}
  • The local variable cntry can be referenced in the template and get the index of the array. Angular 2 will bind the model name from the array with the local variable of template.
  • We have resource called providers which registers class, function or value which are in the context of dependency injection. The service called CountryService can be injected using @Injectable() in thecountry.service.ts file.
  • Next you have implement in the MyListComponent class using OnInithook which indicates that Angular is done creating the component. Using constructor call the _countryService and populate the countrieslist.
  • The ngOnInit() hook is called when done with creating the component and evaluated the inputs.
country.service.ts
import {Injectable} from "angular2/core";
import {COUNTRIES} from "./country.contacts";

//@Injectable() specifies class is available to an injector for instantiation and an injector will display an error when trying to instantiate a class that is not marked as @Injectable()

@Injectable()

//CountryService exposes the getContacts() method that returns the data
export class CountryService {
   getContacts() {
      return Promise.resolve(COUNTRIES); // takes values from country.contacts typescript file
   }
}
country.contacts.ts
import {Country} from "./country";

//storing array of data in Country
export const COUNTRIES: Country[] =[
   {name :"India"},
   {name: "Srilanka"},
   {name: "South Africa"},
   {name: "New Zealand"}
];
country.ts
export interface Country{
   name: string
}

Output

Let's carry out the following steps to see how above code works:
  • Save above HTML code as index.html file as how we created inenvironment chapter and use the above app folder which contains .tsfiles.
  • Open the terminal window and enter the below command:
    npm start
  • After few moments, a browser tab should open and displays the output as shown below.
OR you can run this file in another way:
  • Save above HTML code as angular2_services.html file in your server root folder.
  • Open this HTML file as http://localhost/angular2_services.html and output as below gets displayed.



© Copyright 2015. Website by Way2themes - Published By Gooyaabi Templates