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.
- "author": "",
- "license": "MIT",
- "dependencies": {
- "@angular/common": "~4.0.0",
- "@angular/compiler": "~4.0.0",
- "@angular/core": "~4.0.0",
- "@angular/forms": "~4.0.0",
- "@angular/http": "~4.0.0",
- "@angular/platform-browser": "~4.0.0",
- "@angular/platform-browser-dynamic": "~4.0.0",
- "@angular/router": "~4.0.0",
-
- "angular-in-memory-web-api": "~0.3.0",
- "systemjs": "0.19.40",
- "core-js": "^2.4.1",
- "rxjs": "5.0.1",
- "zone.js": "^0.8.4"
- },
Include http library inside systemjs.config.js
Inlcude the http library inside systemjs.config.js, as shown below.
- map: {
-
- 'app': 'app',
-
-
- '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
- '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
- '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
- '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
- '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
- '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
- '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
- '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
-
-
- 'rxjs': 'npm:rxjs',
- 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
- },
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.
- import { Injectable } from '@angular/core';
- import { Jsonp, URLSearchParams } from '@angular/http';
Also, you will require mapper library, as shown below.
- import 'rxjs/add/operator/map';
The complete code implementation is given below.
- import { Injectable } from '@angular/core';
- import { Jsonp, URLSearchParams } from '@angular/http';
- import { Animal } from '../models/animal';
- import 'rxjs/add/operator/map';
-
- @Injectable()
- export class AnimalService {
- constructor(private jsonp: Jsonp) { }
- private animalUrl = 'http://api.petfinder.com/';
-
-
- getAnimals(animal : string, location: string) {
- const endPoint = 'pet.find'
- let params = new URLSearchParams();
- params.set('key', '555f8155d42d5c9be4705beaf4cce089');
- params.set('location', location);
- params.set('animal', animal);
- params.set('format', 'json');
- params.set('callback', 'JSONP_CALLBACK');
-
- return this.jsonp
- .get(this.animalUrl + endPoint, { search: params })
- .map(response => <Animal[]> response.json().petfinder.pets.pet);
- }
- }
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.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule, JsonpModule } from '@angular/http';
-
- import { AppComponent } from './app.component';
- import { DogListComponent } from './dogs/dog-list.component';
- import {CatListComponent} from './cats/cat-list.component'
- import {BirdListComponent} from './birds/bird-list.component';
-
- import { routing } from './app.routes';
- import {MyFilterPipe} from './filter/MyFilterPipe';
- import { Animal } from '../app/models/animal';
- import {AnimalService} from '../app/dataservices/animal.service';
-
- @NgModule({
- imports: [
- BrowserModule,
- FormsModule,
- HttpModule,
- JsonpModule,
- routing
- ],
- declarations: [
- AppComponent,
- DogListComponent,
- CatListComponent,
- BirdListComponent,
- MyFilterPipe
- ],
- providers: [
- AnimalService
- ],
- bootstrap: [ AppComponent ]
- })
-
- export class AppModule {
- }
Use animal.service inside component
Create one .ts file name "cat-list.component.ts" and import libraries given below.
- import { Component } from '@angular/core';
- import { AnimalService } from '../dataservices/animal.service';
- import { Observable } from 'rxjs/Observable';
Now, call the Service method, as shown below.
- import { Component, OnInit} from '@angular/core';
- import { AnimalService } from '../dataservices/animal.service';
- import { Observable } from 'rxjs/Observable';
- import { Animal } from '../models/animal';
-
- @Component({
- template: `
- <strong>Cats</strong>
- <p>List of cats</p>
- <ul>
- <li *ngFor="let cat of cats | async">
- <span>
- {{cat.name.$t}}
- </span>
- </li>
- </ul>
- `
- })
-
- export class CatListComponent implements OnInit{
- cats: Observable<Animal[]>;
- constructor(private animalService: AnimalService) {
- }
-
- ngOnInit() {
- this.cats = this.animalService.getAnimals('cat', 'texas');
- }
- }
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.