Angular 2 Single Page Apps using Routing – Part 3

If you have not gone through my first two blogs, this might be the right time to go through them: `Angular 2 Single Page Apps using Routing – Part 1′ and `Angular 2 Single Page Apps using Routing – Part 2′.

In this blog, I will show the process for updating app.component.html.

<nav class="navbar navbar-default">
 <div class="container">
 <div class="navbar-header">
 <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
 <span class="sr-only">Toggle navigation</span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 </button>
 <a class="navbar-brand" href="#"><i class="glyphicon glyphicon-briefcase"></i> Pet Care</a>
 </div>
 <div id="navbar" class="navbar-collapse collapse">
 <ul class="nav navbar-nav">
 <li [routerLink]="['/home']" [routerLinkActive]="['active']"><a [routerLink]="['/home']">Home</a></li>
 <li><a href="#">Cats</a></li>
 <li><a href="#">Dogs</a></li>
 </ul>

</div><!–/.nav-collapse –>
</div>
</nav>
<div class=”container page”>
<router-outlet></router-outlet>
</div>

When the browser URL for this application becomes /home, the router matches that URL to the route path /home and displays the HomeComponent after a RouterOutlet (router-outlet) that is placed in the host view’s HTML.

The RouterLink directives on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string to the routerLink.

The RouterLinkActive directive on each anchor tag helps visually distinguish the anchor for the currently selected “active” route. The router adds the active CSS class to the element when the associated RouterLink becomes active.

Now run ‘npm start’ in the command prompt and see the Home page looks as expected.

PetCare Service to Get Pet Data

 Create pet.service.ts file under app folder. Put the following code.

import { Injectable } from '@angular/core';
 import { Jsonp, URLSearchParams } from '@angular/http';
 import 'rxjs/add/operator/map';

@Injectable()
export class PetService {

constructor(private jsonp: Jsonp) { }

private petsUrl = ‘http://api.petfinder.com/’;

findPets(animal : string) {

// http://api.petfinder.com/pet.find?key=[API_KEY]&animal=[ANIMAL]&format=json&location=texas
const endPoint = ‘pet.find’

let params = new URLSearchParams();
params.set(‘key’, ‘[API_KEY]’);
params.set(‘location’, ‘texas’);
params.set(‘animal’, animal);
params.set(‘format’, ‘json’);
params.set(‘callback’, ‘JSONP_CALLBACK’);

return this.jsonp
.get(this.petsUrl + endPoint, { search: params })
.map(response => <string[]> response.json().petfinder.pets.pet);
}

findPetById(id: string) {

const endPoint = ‘pet.get’

let params = new URLSearchParams();
params.set(‘key’, ‘[API_KEY]’);
params.set(‘id’, id);
params.set(‘format’, ‘json’);
params.set(‘callback’, ‘JSONP_CALLBACK’);

// Return response
return this.jsonp
.get(this.petsUrl + endPoint, { search: params })
.map(response => <string[]> response.json().petfinder.pet);
}
}

Here class is decorated with an @Injectable decorator which tells Angular that this class is meant to be used as a provider to other components. Because of Cross-Origin Resource Sharing (CORS) issue JSONP (JavaScript Object Notation with Padding) is used instead of HTTP to make API request. JSONP supports cross-domain JavaScript requests.

The class has 3 members:

  1. Private property which holds the base Url of the API
  2. Method (findPets) to retrieve list of pets based on type (cat/dog)
  3. Method (findPetById) to get details of a pet by it’s Id

URLSearchParams makes it easier to set query parameters and construct URL rather than manually concatenating.

Replace [API_KEY] with key available in the source code. You can also sign-up at https://www.petfinder.com/developers/api-key and get an API key.

Author

  • Vinod Narayanan

    Vinod Narayanan works with Trigent Software as Technical Lead (UI Development). Vinod has over ten years of experience in analysis, design and development, testing and implementation of web based applications. His areas of expertise include Responsive UI and SharePoint Branding.