Getting started with Angular 2: Part 3
#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 serviceFollowing the Angular2 Style Guide,we create a Create a folder named core under src/app if it does not exist. And enter app/core,use 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 Import this module into the application root module, 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
In The get,post,put,delete methods of
Create PostServiceIn the app/core,generate 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 import { PostService } from './post.service'; ... @NgModule({ imports: [ HttpModule,PostService,... ] }) export class CoreModule { } Now Fetch data from backend APIsWe have registered Open posts.component.ts file,replace the hard-coded 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 Here we use a reference to the subscription,and in Now start the application: npm run start Then navigate to http://localhost:4200. You should see the real data from backend APIs. Source codesGrab the sample codes from Github. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |