I am here to continue the discussion around AngularJS 2.0. So far we have discussed about data binding, input properties, output properties, pipes, viewchild, and also about directives in Angular 2.0. Now in this article, I will discuss how to create a Service in Angular 2.0. Also, in case you did not have a look at the previous articles of this series, go through the links mentioned below.
- AngularJS 2.0 From Beginning Introduction of AngularJS 2.0 (Day 1)
- AngularJS 2.0 From Beginning Component (Day 2)
- AngularJS 2.0 From Beginning Data Binding (Day 3)
- AngularJS 2.0 From Beginning Input Data Binding (Day 4)
- AngularJs 2.0 From Beginning - Output Property Binding (Day 5)
- AngularJs 2.0 From Beginning - Attribute Directive (Day 6)
- AngularJs 2.0 From Beginning - Structural Directives (Day 7)
- AngularJs 2.0 From Beginning - Pipes (Day 8)
- AngularJs 2.0 From Beginning - Viewchild (Day 9)
- AngularJs 2.0 From Beginning - Dynamic Grid (Day 10)
An Angular 2 Service is simply a JavaScript function, including its related properties and methods which can perform a particular task or a group of tasks. Actually, Service is a mechanism to use shared responsibilities within one or multiple components. As we already know, we can create components in Angular 2 and nest multiple components together within a component using selector, once our components are nested, we need to manipulate some data within the multiple components. In this case, Service is the best way to handle the situation. Service is the best place where we can take data from other sources or write down some calculations. Similarly, Service can be shared between multiple components as per our need.
Angular 2.0 has greatly simplified the concept of Service over Angular 1.x. In Angular 1, there were service, factory, provider, delegate, value etc. and it was not always clear when to use which one. Angular 2 simply changes the concept of Service. There are two steps for creating a Service in Angular 2.0.
- Create a class with @Injectable decorator.
- Register the class with provider or inject the class by using dependency injection.
@Injectable
@Injectable is actually is a decorator. Decorators are a proposed extension in JavaScript. In short, decorator provides the facility of modifying or using methods, classes, properties and parameters. Injectables are just normal classes (normal objects) and as such, they have no special lifecycle. When an object of your class is created, the class’s constructor is called, so that’s what your “OnInit” would be.
- @Injectable()
- export class SampleService {
- constructor() {
- console.log('Sample service is created');
- }
- }
What is Dependency Injection?
Actually, dependency injection is an important and useful application design pattern. Angular 2.0 has its own dependency injection framework. Basically, it is a coding pattern in which classes receive their dependencies from external sources rather than creating them.
Dependency Injection in Angular 2.0
Dependency injection has always been one of Angular’s biggest features and selling points. It allows us to inject dependencies in different components across our applications, without needing to know how those dependencies are created, or what dependencies they need themselves. However, it turns out that the current dependency injection system in Angular 1.x has some problems that need to be solved in Angular 2.x, in order to build the next generation framework.
Dependency Injection basically consists of three things,
- Injector – The Injector object that exposes APIs to us to create instances of dependencies
- Provider – A Provider is like a commander that tells the injector how to create an instance of a dependency. A provider takes a token and maps that to a factory function that creates an objects.
- Dependency – A Dependency is the type of which an object should be created.
- import { Injectable } from "@angular/core";
- @Injectable()
- export class StudentService {
- private _studentList: Array<any> = [];
- constructor() {
- this._studentList = [{name:'Amit Roy', age:20, city:'Kolkata', dob:'01-01-1997'}];
- }
- returnStudentData(): Array<any> {
- return this._studentList;
- }
- addStudentData(item: any): void {
- this._studentList.push(item);
- }
- }
- <div>
- <h2>Student Form</h2>
- <table style="width:80%;">
- <tr>
- <td>Student Name</td>
- <td><input type="text" [(ngModel)]="_model.name" /></td>
- </tr>
- <tr>
- <td>Age</td>
- <td><input type="number" [(ngModel)]="_model.age" /></td>
- </tr>
- <tr>
- <td>City</td>
- <td><input type="text" [(ngModel)]="_model.city" /></td>
- </tr>
- <tr>
- <td>Student DOB</td>
- <td><input type="date" [(ngModel)]="_model.dob" /></td>
- </tr>
- <tr>
- <td></td>
- <td>
- <input type="button" value="Submit" (click)="submit()" />
- <input type="button" value="Reset" (click)="reset()" />
- </td>
- </tr>
- </table>
- <h3>Student Details</h3>
- <div class="ibox-content">
- <div class="ibox-table">
- <div class="table-responsive">
- <table class="responsive-table table-striped table-bordered table-hover">
- <thead>
- <tr>
- <th style="width:40%;">
- <span>Student's Name</span>
- </th>
- <th style="width:15%;">
- <span>Age</span>
- </th>
- <th style="width:25%;">
- <span>City</span>
- </th>
- <th style="width:20%;">
- <span>Date of Birth</span>
- </th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let item of _source; let i=index">
- <td><span>{{item.name}}</span></td>
- <td><span>{{item.age}}</span></td>
- <td><span>{{item.city}}</span></td>
- <td><span>{{item.dob}}</span></td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- import { Component, OnInit, ViewChild } from '@angular/core';
- import { StudentService } from './app.service.student';
- @Component({
- moduleId: module.id,
- selector: 'student',
- templateUrl: 'app.component.student.html',
- providers: [StudentService]
- })
- export class StudentComponent implements OnInit {
- private _model: any = {};
- private _source: Array<any>;
- constructor(private _service: StudentService) {
- this._source = this._service.returnStudentData();
- }
- ngOnInit(): void {
- }
- private submit(): void {
- if (this.validate()) {
- this._service.addStudentData(this._model);
- this.reset();
- }
- }
- private reset(): void {
- this._model = {};
- }
- private validate(): boolean {
- debugger;
- let status: boolean = true;
- if (typeof (this._model.name) === "undefined") {
- alert('Name is Blank');
- status = false;
- return;
- }
- else if (typeof (this._model.age) === "undefined") {
- alert('Age is Blank');
- status = false;
- return;
- }
- else if (typeof (this._model.city) === "undefined") {
- alert('City is Blank');
- status = false;
- return;
- }
- else if (typeof (this._model.dob) === "undefined") {
- alert('dob is Blank');
- status = false;
- return;
- }
- return status;
- }
- }
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from "@angular/forms";
- import { StudentComponent } from './src/app.component.student';
- @NgModule({
- imports: [BrowserModule, FormsModule],
- declarations: [StudentComponent],
- bootstrap: [StudentComponent]
- })
- export class AppModule { }
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app.module';
- const platform = platformBrowserDynamic();
- platform.bootstrapModule(AppModule);
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular2 - Service</title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link href="../resources/style/style1.css" rel="stylesheet" />
- <!-- Polyfill(s) for older browsers -->
- <script src="../node_modules/core-js/client/shim.min.js"></script>
- <script src="../node_modules/zone.js/dist/zone.js"></script>
- <script src="../node_modules/reflect-metadata/Reflect.js"></script>
- <script src="../node_modules/systemjs/dist/system.src.js"></script>
- <script src="../systemjs.config.js"></script>
- <script>
- System.import('app').catch(function (err) { console.error(err); });
- </script>
- </head>
- <body>
- <student>Loading</student>
- </body>
- </html>


Join the conversation! Your thoughts help the community grow.