Getting Started with AngularJS 1.5 and ES6: part2

HTTP

In the posts component, the posts data is initialized in th $onInit method of posts controller class.

In a real world application, it could be fecthed from external resources, such as third party APIs. Angular service is a good place to do this work.

Service

Extract posts data codes and put into a standalone class called Post service.

common/services/post.service.js:

class Post {

  constructor() {

  }
  
  getAllPosts(){
	return [
       { id: 1, title: 'Getting started with REST', content: 'Content of Getting started with REST', createdAt: '9/22/16 4:15 PM' },
       { id: 2, title: 'Getting started with AngularJS 1.x', content: 'Content of Getting started with AngularJS 1.x', createdAt: '9/22/16 4:15 PM' },
       { id: 3, title: 'Getting started with Angular2', content: 'Content of Getting started with Angular2', createdAt: '9/22/16 4:15 PM' },
    ];
  }

In posts.controller.js and call getAllPosts to get all posts data.

class PostsController {
  constructor(Post) {
    'ngInject';

    this._Post = Post;
	...
  }
  
  $onInit() {
    console.log("initializing Posts...");
	this.posts=this._Post.getAllPosts();
  }
}  

Note, ngInject in this constructor will tell Webpack to use ngAnnotate to wire its dependencies when loading this class.

In order to make this Post is injectable here, you have to declare it as an Angular service.

Add the following codes into common/services/index.js.

import PostService from './post.service';
//...
let commonServicesModule = angular.module('app.common.services', [])
  //...
  .service('Post', PostService)
  /...

Add commonServices as a dependency of posts module.

let postsModule = angular.module('posts', 
							[commonSevices,....

Run the application again and make sure it works as before.

Beside Angular service, there are other two facilities existed in Angular: factory and provider. They all can be considered as service, but they are designated for different purposes.

factory applies the Factory pattern in codes, should return a new instance for every call.

We have used providers in before codes, such as $stateProvider. It allow user to configure the service in app.config().

More detailed explanation, read this stackoverflow discussion about difference between service, factory and provider.

Next, let's fetch data from remote APIs.

HTTP

Angular has built-in $http service to shake hands with remote APIs.

To demonstrate HTTP interaction, I used another Java EE 7/Jaxrs REST API sample project I created to serve as backend APIs.

There are some variants in this repository, we used the cdi one in this project.

Follow the Getting started guide to deploy it into a running Wildfly 10.x, it serves several APIs for use.

UriHttp MethodRequestResponseDescription
/postsGET200, [{'id':1, 'title'},{}]Get all posts
/postsPOST{'title':'test title','content':'test content'}201Create a new post
/posts/{id}GET200, {'id':1, 'title'}Get a post by id
/posts/{id}PUT{'title':'test title','content':'test content'}204Update a post
/posts/{id}DELETE204Delete a post

Configure the api base url in app.constants.js file.

const AppConstants = {
  //...
  api: 'http://localhost:8080/blog-api-cdi/api'
};

//...

Inject $http in our Post service, and fecth posts data from our APIs.

class Post {

  constructor(AppConstants, $http, $q) {
    'ngInject';

    this._AppConstants = AppConstants;
    this._$http = $http;
    this._$q = $q;
  }
  
   query(keyword) {
    let deferred = this._$q.defer();
    // Create the $http object for this request
    let request = {
      url: this._AppConstants.api + '/posts',
      method: 'GET',
      params: !!keyword ? { 'q': keyword } : null
    };

    this._$http(request)
      .then(
        (res) => deferred.resolve(res.data),
        (err) => deferred.reject(err)
      );

    return deferred.promise;
  }
  
export default Post;  

The GET /posts APIs can accept a query parameter q to search posts in database. query method return a Promise, please read the $q online docs to get more details about the Angular promise.

Modify posts controller class to use query to fetch posts data.

  $onInit() {
    console.log("initializing Posts...");
    this.searchPosts();
  }

  searchPosts() {
    this._Post
      .query(this.q)
      .then(
      (res) => this.posts = res
      );
  }

Now run the applicaiton again, everything should be working as expected.

Check the sample codes.

转载于:https://my.oschina.net/hantsy/blog/754524

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值