Interacting with Services & API: Angular 2
In this post we are going to create an Angular 2
application from scratch, the target of this post is to
explain the process to create a service and use an API to
get the data from that, where we will also see, how to
handle the response of the API, preview the response on
the view and handle the exceptions if any found in the
API call.
Let’s start with the process: Just clone this
quickstart AngularJs 2 repo
git clone
https://github.com/angular/quickstart.gi
t ngService
we will work over this application, don’t worry
we’ll remove everything else that is not necessary
for this application.
after cloning the same run ` npm install` it will
install all the required dependencies to run the
application, now run `npm start` this will run the
application on the default port …:3000 and you
will see Hello Angular. Hurray now we are ready to
work over it.
We will be using the github API to interact with
and get data: here it is.
https://api.github.com/users/
Hope you already opened the cloned project in your
favorite editor, in my case it is VS Code. Just head
to the src -> app folder in the application, here you
will see app.component this is the already created
component in the cloned project. I assume you are
already aware about the basics of AngularJs 2 like,
components, basic TypeScript etc.
Let’s start coding: Create a new service under app
folder for AppComponent, so just right click on app
folder and create a new file name: data.service.ts.
data.service.ts
1
import 'rxjs/add/operator/map';
2
import 'rxjs/add/observable/of';
3
import 'rxjs/add/observable/throw';
4
import 'rxjs/add/operator/catch';
5
import {Observable} from
'rxjs/Observable';
6
7
import {Component, Injectable} from
'@angular/core';
8
import {Http, Response } from
'@angular/http';
9
10
@Injectable()
11
export class DataService {
12
13
constructor(private http: Http){}
14
15
getUserData(){
16
return
this.http.get('/app/trainingData.json
').map(
17
(response: Response) =>
response.json()
18
)
19
.catch(this._errorHandler);
20
}
21
22
console.error("Problem in
service :::: " + error);
23
return Observable.throw(error ||
"Server Error");
24
}
25
}
For now i have created a file
“trainingData.json” and pasted the data that
came from the github api, and giving the path
of this data file in my http get call.
here we have created the data service that is hitting
the http request to get the data from that api, and
we are catching the error there as well, why we
doing this is because if our api doesn’t respond as
expected we will catch the error there and our view
will not distort at all.
now, app.component.ts
1
import { Component } from
'@angular/core';
2
import {DataService} from
"./data.service";
3
import {Http } from '@angular/http';
4
5
@Component({
6
selector: 'my-app',
7
template: ` <button
(click)="loadData()">Load
Data</button>
8
<h1>Hi : {{userData.login}}</h1>
9
`
10
})
11
export class AppComponent {
12
constructor(private dataService:
DataService){}
13
14
userData:any=[];
15
16
loadData(){
17
this.dataService.getUserData().subscr
ibe(
18
(data) => this.userData = data
19
)
20
}
21
}
So when you click the button, the template tag
contains a button with a function, loadData(),
that will show the data from the
trainingData.json.
Download the code from here: Github
https://github.com/nikhilknoldus/ngService