跳至主要内容

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 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}`, body, { 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:
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,
    ...
  ],
  providers: [
    ApiService,
    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',
    //     createdAt: '9/22/16 4:15 PM'
    //   },
    //   {
    //     id: 3,
    //     title: 'Getting started with Angular2',
    //     home: 'Home of Getting started with Angular2',
    //     createdAt: '9/22/16 4:15 PM'
    //   },
    // ];
  }

  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.
Posts works

Source codes

Grab the sample codes from Github.

评论

此博客中的热门博文

AngularJS CakePHP Sample codes

Introduction This sample is a Blog application which has the same features with the official CakePHP Blog tutorial, the difference is AngularJS was used as frontend solution, and CakePHP was only use for building backend RESR API. Technologies AngularJS   is a popular JS framework in these days, brought by Google. In this example application, AngularJS and Bootstrap are used to implement the frontend pages. CakePHP   is one of the most popular PHP frameworks in the world. CakePHP is used as the backend REST API producer. MySQL   is used as the database in this sample application. A PHP runtime environment is also required, I was using   WAMP   under Windows system. Post links I assume you have some experience of PHP and CakePHP before, and know well about Apache server. Else you could read the official PHP introduction( php.net ) and browse the official CakePHP Blog tutorial to have basic knowledge about CakePHP. In these posts, I tried to follow the steps describ

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa