REST Service Call With Angular 4

Introduction

AngularJS uses $http Services to send AJAX requests for making REST Service calls. It gives response data to the client in the form of JSON. Some additional concepts like defer, promise are used.

 
Angular 4 REST Service call mechanism is totally different from AngularJS. Now, it is more easy to use. It has removed additional things like defer, promise etc. to make it more easy. Angular 4 has introduced library to make REST Service call named "@angular/http".

Code explanation

Include http library into package.json file

package.json file is used to define all the dependencies to download, compile and execution mechanism of the project. You will be required to include library given below of Angular 4 for REST Service, as shown below.
  1. "author""",  
  2.   "license""MIT",  
  3.   "dependencies": {  
  4.     "@angular/common""~4.0.0",  
  5.     "@angular/compiler""~4.0.0",  
  6.     "@angular/core""~4.0.0",  
  7.     "@angular/forms""~4.0.0",  
  8.     "@angular/http""~4.0.0",  
  9.     "@angular/platform-browser""~4.0.0",  
  10.     "@angular/platform-browser-dynamic""~4.0.0",  
  11.     "@angular/router""~4.0.0",  
  12.   
  13.     "angular-in-memory-web-api""~0.3.0",  
  14.     "systemjs""0.19.40",  
  15.     "core-js""^2.4.1",  
  16.     "rxjs""5.0.1",  
  17.     "zone.js""^0.8.4"  
  18.   },  
Include http library inside systemjs.config.js

Inlcude the http library inside systemjs.config.js, as shown below.
  1. map: {  
  2.       // our app is within the app folder  
  3.       'app''app',  
  4.   
  5.       // angular bundles  
  6.       '@angular/core''npm:@angular/core/bundles/core.umd.js',  
  7.       '@angular/common''npm:@angular/common/bundles/common.umd.js',  
  8.       '@angular/compiler''npm:@angular/compiler/bundles/compiler.umd.js',  
  9.       '@angular/platform-browser''npm:@angular/platform-browser/bundles/platform-browser.umd.js',  
  10.       '@angular/platform-browser-dynamic''npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',  
  11.       '@angular/http''npm:@angular/http/bundles/http.umd.js',  
  12.       '@angular/router''npm:@angular/router/bundles/router.umd.js',  
  13.       '@angular/forms''npm:@angular/forms/bundles/forms.umd.js',  
  14.   
  15.       // other libraries  
  16.       'rxjs':                      'npm:rxjs',  
  17.       'angular-in-memory-web-api''npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'  
  18.     },  
Create animal.service.ts

Create one ts file animal.service.ts inside dataservice folder. This Service file will be responsible for making REST Service call, which is based on the parameters.
 
The libraries given below are very important to include the code given below.
  1. import { Injectable }    from '@angular/core';  
  2. import { Jsonp, URLSearchParams } from '@angular/http';  
Also, you will require mapper library, as shown below.
  1. import 'rxjs/add/operator/map';  
The complete code implementation is given below.
  1. import { Injectable }    from '@angular/core';  
  2. import { Jsonp, URLSearchParams } from '@angular/http';  
  3. import { Animal } from '../models/animal';  
  4. import 'rxjs/add/operator/map';  
  5.   
  6. @Injectable()  
  7. export class AnimalService {  
  8.   constructor(private jsonp: Jsonp) { }  
  9.   private animalUrl = 'http://api.petfinder.com/';  
  10.   
  11. // Returns list of animals based input parameters.  
  12.   getAnimals(animal : string,  location: string) {  
  13.     const endPoint = 'pet.find'  
  14.     let params = new URLSearchParams();  
  15.     params.set('key''555f8155d42d5c9be4705beaf4cce089');  
  16.     params.set('location', location);  
  17.     params.set('animal', animal);  
  18.     params.set('format''json');  
  19.     params.set('callback''JSONP_CALLBACK');  
  20.     // Returns response  
  21.    return this.jsonp  
  22.               .get(this.animalUrl + endPoint, { search: params })  
  23.               .map(response => <Animal[]> response.json().petfinder.pets.pet);  
  24.   }  
  25. }  
Animal class must be set as @Injectable() Decorator because this class will be injected as a Service to another class.
 
Here, method URLSearchParams() provides to add different kind of request parameters as we were passing as a header during $http.get or $http.post in AngulerJS.
 
jsonp.get() method takes the input of two parameters - rest service url and header details. It returnes the response and that response is being mapped to Animal model type of object array with JSON format.
 
Import and inject  into app.module.ts

Now, import and inject the AnimalService class into app.module.ts class, as shown below.
  1. import { NgModule }       from '@angular/core';  
  2. import { BrowserModule }  from '@angular/platform-browser';  
  3. import { FormsModule }    from '@angular/forms';  
  4. import { HttpModule, JsonpModule } from '@angular/http';  
  5.   
  6. import { AppComponent } from './app.component';  
  7. import { DogListComponent } from './dogs/dog-list.component';  
  8. import {CatListComponent} from './cats/cat-list.component'  
  9. import {BirdListComponent} from './birds/bird-list.component';  
  10.   
  11. import { routing } from './app.routes';  
  12. import {MyFilterPipe} from './filter/MyFilterPipe';  
  13. import { Animal } from '../app/models/animal';  
  14. import {AnimalService} from '../app/dataservices/animal.service';  
  15.   
  16. @NgModule({  
  17.   imports: [  
  18.     BrowserModule,  
  19.     FormsModule,  
  20.     HttpModule,  
  21.     JsonpModule,  
  22.     routing  
  23.   ],  
  24.   declarations: [  
  25.     AppComponent,  
  26.     DogListComponent,  
  27.     CatListComponent,  
  28.     BirdListComponent,  
  29.     MyFilterPipe  
  30.   ],  
  31.    providers: [  
  32.     AnimalService  
  33.   ],  
  34.   bootstrap: [ AppComponent ]  
  35. })  
  36.   
  37. export class AppModule {  
  38. }  
Use animal.service inside component

Create one .ts file name "cat-list.component.ts" and import libraries given below.
  1. import { Component } from '@angular/core';  
  2. import { AnimalService } from '../dataservices/animal.service';  
  3. import { Observable } from 'rxjs/Observable';  
Now, call the Service method, as shown below.
  1. import { Component, OnInit} from '@angular/core';  
  2. import { AnimalService } from '../dataservices/animal.service';  
  3. import { Observable } from 'rxjs/Observable';  
  4. import { Animal } from '../models/animal';  
  5.   
  6. @Component({  
  7.   template: `  
  8.     <strong>Cats</strong>  
  9.     <p>List of cats</p>  
  10.       <ul>  
  11.       <li *ngFor="let cat of cats | async">  
  12.         <span>  
  13.             {{cat.name.$t}}  
  14.         </span>  
  15.       </li>  
  16.     </ul>  
  17.     `  
  18. })  
  19.   
  20. export class CatListComponent implements OnInit{  
  21.  cats: Observable<Animal[]>;  
  22.   constructor(private animalService: AnimalService) {  
  23.   }  
  24.   
  25.   ngOnInit() {  
  26.     this.cats = this.animalService.getAnimals('cat''texas');  
  27.   }  
  28. }  
Here, I added OnInit inside import because I want to make Service call on page load. Hence, CatListComponent class has implemented OnInit interface, which provides method ngOnInit to fire on page load.
 
Here, Observable has been used. It has wide range of discussions. I will explain this in another article. In short, it pushes value changes to the components and the Services, which subscribe to changes.

Output


Please refer to attached zip code for more details.
 
Steps to execute
 
Node.js must be installed into your machine.

Go to root folder routingpractice ~~ Open command prompt ~~ type npm start ~~ Application will compile and launch on the browser.
~~ click Cat tab ~~ You will get list of cats.
 
Conclusion

Angular 4 REST Service call mechanism is very optimized, fast and easy to use. Jsonp and URLSearchParams are very important parts of http library of Angular 4.

Up Next
    Ebook Download
    View all
    Learn
    View all