#Interact with backend APIs
Similar with the serise of Getting started with Angular 1.5 and ES6,after a glance at Angular2,we will try to fecth data from the real backend APIs.
In this Angular2 sample,we still reuse the sample codes of Java EE 7 and Jaxrs RESTful APIs to serve backen RESTful APIs.
There are several variants in the root folder of this repository,we use the cdi for our case. Following the Getting started wiki page to deploy it into a running wildfly server.
Create a common API service
Following the Angular2 Style Guide,we create a CoreModule
to share the service like singleton class to the application scope.
Create a folder named core under src/app if it does not exist. And enter app/core,use ng
to generate the a service naned Api
.
ng g service api
It will create an api.service.ts and an api.service.spec.ts in this folder.
Create a module specific purpose file named core.module.ts,fill the following home.
import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { ApiService } from './api.service'; @NgModule({ imports: [ HttpModule,... ],providers: [ ApiService,... ] }) export class CoreModule { }
We will use http related features to interact with backend APIs,so imports HttpModule
from @angular/http
.
Import this module into the application root module,AppModule
.
import { CoreModule } from './core/core.module'; ... @NgModule({ ... imports: [ //app modules CoreModule,... ] }) export class AppModule { }
The complete code of api.service.ts.
import { Injectable,Inject} from '@angular/core'; import { Http,Headers,RequestOptions,Response,URLSearchParams } from '@angular/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class ApiService { private headers: Headers = new Headers({ 'Content-Type': 'application/json','Accept': 'application/json' }); private API_URL: string = 'http://localhost:8080/blog-api-cdi/api'; constructor(private http: Http) { } public get(path: string,term?: any): Observable<any> { console.log('get resources from url:' + `${this.API_URL}${path}`); let search = new URLSearchParams(); if (term) { Object.keys(term).forEach(key => search.set(key,term[key])); } return this.http.get(`${this.API_URL}${path}`,{ search,headers: this.headers }) .map(this.extractData) .catch(this.handleError); } public post(path: string,data: any): Observable<any> { let body = JSON.stringify(data); return this.http.post(`${this.API_URL}${path}`,body,{ headers: this.headers }) //.map(this.extractData) .catch(this.handleError); } public put(path: string,data: any): Observable<any> { let body = JSON.stringify(data); return this.http.put(`${this.API_URL}${path}`,{ headers: this.headers }) //.map(this.extractData) .catch(this.handleError); } public delete(path: string): Observable<any> { return this.http.delete(`${this.API_URL}${path}`,{ headers: this.headers }) //.map(this.extractData) .catch(this.handleError); } public setHeaders(headers) { Object.keys(headers).forEach(header => this.headers.set(header,headers[header])); } public setHeader(key: string,value: string) { this.headers.set(key,value); } public deleteHeader(key: string) { if (this.headers.has(key)) { this.headers.delete(key); } else { console.log(`header:${key} not found!`); } } private extractData(res: Response): Array<any> | any { if (res.status >= 200 && res.status <= 300) { return res.json() || {}; } return res; } private handleError(error: any) { // In a real world app,we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message // let errMsg = (error.message) ? error.message : // error.status ? `${error.status} - ${error.statusText}` : 'Server error'; // console.error(errMsg); // log to console instead console.log(error); return Observable.throw(error); } }
This class is a simple wrapper of Angular 2 built-in Http
service,but provides hooks to add or remove headers which is useful when we disscuss authentication in further posts.
@Injectable()
is a property decorator,it means this class is injectable.
In constructor(private http: Http)
,Angular 2 DI performs magics,Http
service is injected at runtime and assigned to a http reference.
The get,post,put,delete methods of Http
return a RxJS Observable
. There is a good article from Jaxenter to describe RxJS operators,Reactive Programming HTTP and Angular 2.
handleError
is an exception handler,in a real world application,we could gather the errors and send to a logging monitor server to track the application errors. In this case,print the error in console simply.
Create PostService
In the app/core,generate PostService
.
ng g service post ``` Replace the home of *post.service.ts* with following: ```typescript import { Injectable } from '@angular/core'; import { ApiService } from './api.service'; import { Post } from './post.model'; import { Comment } from './comment.model'; @Injectable() export class PostService { private path: string = '/posts'; constructor(private api: ApiService) { } getPosts(term?: any) { return this.api.get(`${this.path}`,term); } getPost(id: number) { return this.api.get(`${this.path}/${id}`); } savePost(data: Post) { console.log('saving post:' + data); return this.api.post(`${this.path}`,data); } updatePost(id: number,data: Post) { console.log('updating post:' + data); return this.api.put(`${this.path}/${id}`,data); } deletePost(id: number) { return this.api.delete(`${this.path}/${id}`); } saveComment(id: number,data: Comment) { return this.api.post(`${this.path}/${id}/comments`,data); } getCommentsOfPost(id: number) { return this.api.get(`${this.path}/${id}/comments`); } }
In the same folder,create two model classes to describe the models of Post and comment.
touch post.model.ts touch comment.model.ts
Content of post.model.ts:
export interface Post { id?: number; title: string; content: string; createdAt?: string; createdBy?: string; }
Content of comment.model.ts:
export interface Comment { id?: number; content: string; createdBy?: string; createdAt?: string; }
Register PostService
in CoreModule
.
import { PostService } from './post.service'; ... @NgModule({ imports: [ HttpModule,PostService,... ] }) export class CoreModule { }
Now PostService
is ready for use.
Fetch data from backend APIs
We have registered CoreModule
in AppModule
,it will be available in all modules,it is no needs to import it in every component modules.
Open posts.component.ts file,replace the hard-coded posts
with PostService.getPost
.
The complete codes of posts.component.ts:
import { Component,OnInit,OnDestroy } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Post } from '../core/post.model'; import { PostService } from '../core/post.service'; import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'app-posts',templateUrl: './posts.component.html',styleUrls: ['./posts.component.css'] }) export class PostsComponent implements OnInit,OnDestroy { q: string = ''; posts: Post[]; sub: Subscription; constructor(private postService: PostService) { } ngOnInit() { this.sub = this.postService.getPosts(null).subscribe( res => this.posts = res ); // this.posts = [ // { // id: 1,// title: 'Getting started with REST',// home: 'Home of Getting started with REST',// createdAt: '9/22/16 4:15 PM' // },// { // id: 2,// title: 'Getting started with AngularJS 1.x',// home: 'Home of Getting started with AngularJS 1.x',// { // id: 3,// title: 'Getting started with Angular2',// home: 'Home of Getting started with Angular2',// ]; } ngOnDestroy() { if (this.sub) { this.sub.unsubscribe(); } } }
In constructor
method,PostService
is injected,and in ngOnInit
,it subscribes PostService.getPost
and fecthes the posts data.
Here we use a reference to the subscription,and in ngOnDestroy
,call sub.unsubscribe
to release the resources.
Now start the application:
npm run start
Then navigate to http://localhost:4200. You should see the real data from backend APIs.
Source codes
Grab the sample codes from Github.