Every dynamic application needs to access the data from some external source, which can be from some database or from other resources. To access the data from the external sources in Angular 2, Service is the answer. Services offer reusability; i.e. , they can be used throughout the application across the components. Also, adding the Services to Angular application makes your component free from data access code & more focus oriented on displaying view logic.
Service in Angular2 has the features given below.
- They are singleton objects (i.e. only one instance of Angular Service exists throughout the Application).
- They are capable of returning the data in the form of promises (who is quite familiar with Angular1.x) as well as in the form of Observables (which is the next generation JavaScript feature).
- Service class is decorated with @Injectable() decorator (The @Injectable() decorator is required only if our service class is making use of some Angular injectables like http service within it).
NOTE
You can register your Service either globally, at the module level or at the component level.
To demonstrate the Service, we’ll separate employee collection, which has for now been directly loaded inside the EmpListComponent to our new service EmpService & now our Service will be responsible to return the data to the EmpListComponent. Hence, let’s create a new Service with the name “emp.service.ts” inside our “emp” folder.
emp.service.ts
- import { Injectable } from '@angular/core';
- import { IEmployee } from './employee';
-
- @Injectable()
- export class EmpService {
- constructor() {
- }
-
- public getEmployees(): IEmployee[] {
- return [
- {
- "empId": "E001",
- "name": "Leanne Graham",
- "email": "[email protected]",
- "phone": "1-770-736-8031 x56442",
- "photo": "./app/assets/imgs/face1.jpg",
- "salary": 50000,
- "appraisalRating": 4
- },
- {
- "empId": "E002",
- "name": "Ervin Howell",
- "email": "[email protected]",
- "phone": "210.067.6132",
- "photo": "./app/assets/imgs/face2.jpg",
- "salary": 65000,
- "appraisalRating": 3.5
- },
- {
- "empId": "E003",
- "name": "Clementine Bauch",
- "email": "[email protected]",
- "phone": "1-477-935-8478 x6430",
- "photo": "./app/assets/imgs/face3.jpg",
- "salary": 62500,
- "appraisalRating": 3.75
- },
- {
- "empId": "E004",
- "name": "Patricia Lebsack",
- "email": "[email protected]",
- "phone": "(254)954-1289",
- "photo": "./app/assets/imgs/face4.png",
- "salary": 49500,
- "appraisalRating": 4.25
- },
- {
- "empId": "E005",
- "name": "Chelsey Dietrich",
- "email": "[email protected]",
- "phone": "493-170-9623 x156",
- "photo": "./app/assets/imgs/face5.jpg",
- "salary": 25000,
- "appraisalRating": 3.25
- },
- {
- "empId": "E006",
- "name": "Mrs. Dennis Schulist",
- "email": "[email protected]",
- "phone": "1-463-123-4447",
- "photo": "./app/assets/imgs/face6.ico",
- "salary": 100000,
- "appraisalRating": 4.5
- },
- {
- "empId": "E007",
- "name": "Kurtis Weissnat",
- "email": "[email protected]",
- "phone": "010-692-6593 x09125",
- "photo": "./app/assets/imgs/face7.png",
- "salary": 36900,
- "appraisalRating": 4
- }
- ];
- }
- }
Since our Service is ready, it’s the time to register the Service class. To register, we’ll be using “Providers” property/option of @NgModule. Our updated file is given below.
app.module.ts file
-
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { BrowserModule } from '@angular/platform-browser';
-
- import { AppComponent } from './app.component';
- import { EmployeeListComponent } from './emp/emp-list.component';
- import { EmployeeSearchPipe } from './emp/emp-search.pipe';
- import { FormatSalaryDirective } from './emp/emp-formatsalary.directive';
- import { ARStarComponent } from './shared/ar-star.component';
- import { EmpService } from './emp/emp.service';
-
- @NgModule({
- imports: [BrowserModule, FormsModule],
- declarations: [AppComponent, EmployeeListComponent, EmployeeSearchPipe, ARStarComponent, FormatSalaryDirective],
- providers: [EmpService],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Try to run the Application and you’ll find that our app is still working, as expected.
Our Service class is decorated with @Injectable, which is not really required, since we are not using any Angular injectables now. Hence, even if you comment that line, our application still works perfectly. The snapshot is given below after commenting @Injectable() decorator from our Service class.
Our Service class still has static data loaded into the array. We can make it a little more complex by adding our data into a JSON file & via Http request, we can try to load the data. This will be a good demonstration of how to create a realistic Angular2 Service.
I’ve created a new “emp-data.json” file inside our emp folder & copied our array collection from our Service to that JSON file. Now, inside our EmpService class, we’ll make use of httpService to load the contents of this file. Http Service lies inside HttpModule, so our first step for using Http Service would be to load the HttpModule & register it with @NgModule in the “imports” section inside our app.module.ts file.
Here, our updated app.module.ts file is given below.
-
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { BrowserModule } from '@angular/platform-browser';
- import { HttpModule } from '@angular/http';
-
- import { AppComponent } from './app.component';
- import { EmployeeListComponent } from './emp/emp-list.component';
- import { EmployeeSearchPipe } from './emp/emp-search.pipe';
- import { FormatSalaryDirective } from './emp/emp-formatsalary.directive';
- import { ARStarComponent } from './shared/ar-star.component';
- import { EmpService } from './emp/emp.service';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule],
- declarations: [AppComponent, EmployeeListComponent, EmployeeSearchPipe, ARStarComponent, FormatSalaryDirective],
- providers: [EmpService],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Now, we’ve HttpModule registered with our app module. We can access it anywhere within our application. The updated code is given below.
emp.service.ts
- import { Injectable } from '@angular/core';
- import { Http } from '@angular/http';
- import { IEmployee } from './employee';
-
- @Injectable()
- export class EmpService {
-
- constructor(private http: Http) {
- }
- ...
- }
NOTE
Now, we are injecting http Angular Service. We need to have @Injectable decorated above our Service class.
In Angular2, the Service can either return the data in the form of Promises or in the form of Observables. In this demo, we’ll focus more on how to return the data through observables. You can think of Observables as an array, whose elements come asynchronously over a period of time. Observables are next JavaScript features; i.e., to make use of Observables in the current application, we’ll have to make use of some 3rd party library & the name of the library is Rx/Js. This library provides the support for Observables & its methods. For more information about the Rx/Js library, you can checkout this link.
There are certain differences between Observables & Promises.
- Through Promise, we can return only a single value at a time but through Observables, we can return multiple values.
- Observables are more advanced than Promises; i.e. they are cancellable & Promises are not
The points given above are clearly mentioned in this video.
Since we’ll be using Rx/Js library throughout the application, I’m importing this library in app.module.ts file, using import statement given below.
import 'rxjs/Rx'; // this will load the whole Rx/Js library
Since our Rx/Js library is loaded, we can use Observables throughout our application, wherever required. The updated code for EmpService is given below.
emp.service.ts file
- import { Injectable } from '@angular/core';
- import { Http, Response } from '@angular/http';
- import { IEmployee } from './employee';
- import { Observable } from 'rxjs/Observable';
-
- @Injectable()
- export class EmpService {
-
- private _repositoryURL: string = "app/emp/emp-data.json";
-
- constructor(private http: Http) {
- }
-
- public getEmployees(): Observable<IEmployee[]> {
- return this.http.get(this._repositoryURL)
- .map((response: Response) => { return <IEmployee[]>response.json() })
- .catch(this.handleError);
- }
-
- private handleError(errorResponse: Response) {
- console.log(errorResponse.statusText);
- return Observable.throw(errorResponse.json().error || "Server error");
- }
- }
You can see return type of getEmployees() method is Observable<IEmployee[]> & from within that function, we are returning employee[] by typecasting JSON data to IEmployee[] type. We are making use of Rx/Js library map function to transform JSON data to IEmployee[]. Map function helps us to transform the Observable values before they're returned. For more information on other Rx/Js library function, refer the link.
Now our Service class is returning Observables. To access Observables data, we need to subscribe/register handler for handling the emitted values. Here is the updated code for EmpListComponent.
emp-list.component.ts
- import { Component, OnInit } from '@angular/core';
- import { IEmployee } from './employee';
- import { EmpService } from './emp.service';
-
- @Component({
- selector: 'emp-list',
- templateUrl: './app/emp/emp-list.component.html'
- })
- export class EmployeeListComponent implements OnInit {
- pageTitle: string = "Employee Details";
- imageWidth: number = 50;
- imageHeight: number = 50;
- filterByName: string = "";
- showImageColumn: boolean = false;
- eRating: string = "";
- employees: IEmployee[];
- errorMessage: string;
-
- constructor(private empService: EmpService) {
- this.employees = [];
- }
-
- ngOnInit(): void {
- let self = this;
- self.empService.getEmployees().subscribe(empData => this.employees = empData,
- error => this.errorMessage = <any>error);
- }
-
-
-
-
- toggleImageColumn(): void {
- this.showImageColumn = !this.showImageColumn;
- }
-
-
-
-
- ratingClickedHandler(message: string): void {
- let self = this;
- self.eRating = message;
- }
- }
Try to run the application and it works as expected.
In our next post, we’ll continue further. Until then, you can download the solution and test it locally at your end. I am uploading the solution file with this post; but I won’t be able to upload the node_modules folder because of the heavy size. Thus, I request you install NPM before you run the application.