文档章节

Getting Started with AngularJS 1.5 and ES6: part2

hantsy
 hantsy
发布于 2016/10/05 09:07
字数 619
阅读 17
收藏 0

3 月,跳不动了?>>>

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.

Uri Http Method Request Response Description
/posts GET 200, [{'id':1, 'title'},{}] Get all posts
/posts POST {'title':'test title','content':'test content'} 201 Create a new post
/posts/{id} GET 200, {'id':1, 'title'} Get a post by id
/posts/{id} PUT {'title':'test title','content':'test content'} 204 Update a post
/posts/{id} DELETE 204 Delete 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.

© 著作权归作者所有

hantsy
粉丝 113
博文 88
码字总数 78079
作品 0
浦东
程序员
私信 提问
加载中

评论(0)

linux 环境下 angular2 生成component 报错 ELOOP:too many symbolic links encountered, stat

adaptercat@debian :/project/angular/AngularTest/src/app$ ng generate component t Error: ELOOP: too many symbolic links encountered, stat '/project/angular/AngularTest/node_modul......

adaptercat
2017/10/10
619
1
AngularJS2.0 教程系列(一)

Why Angular2 Angular1.x显然非常成功,那么,为什么要剧烈地转向Angular2? 性能的限制 AngularJS当初是提供给设计人员用来快速构建HTML表单的一个内部工具。随着时间的推移,各种特性 被加...

笔阁
2015/07/22
2.5W
1
All About Angular 2.0

angular All About Angular 2.0Posted by Rob Eisenberg on November 6th, 2014. Have questions about the strategy for Angular 2.0? This is the place. In the following article I'll e......

Ethan_prog
2015/03/06
156
0
[Angular Material完全攻略] Day 02 - 环境设定 & 安装 & Hello World

今天我们将开始正式迈入Angular Material的世界,要学习使用Angular Material打造高品质及高质感的网页,当然要从安装Angular Material套件开始,本篇文章就来介绍基本的Angular Material安装...

readilen
2018/05/21
0
0
ngular2 VS Angular4 深度对比:特性、性能

在Web应用开发领域,Angular被认为是最好的开源JavaScript框架之一。 Google的Angular团队已于3月23日发布了Angular4,而期待已久的Angular2版本则是之前版本的完全重构。 对于成熟的开发人员...

机器的心脏
2018/06/02
0
0

没有更多内容

加载失败,请刷新页面

加载更多

C语言动态内存分配:(一)malloc/free的实现及malloc实际分配/释放的内存

一、malloc/free概述 malloc是在C语言中用于在程序运行时在堆中进行动态内存分配的库函数。free是进行内存释放的库函数。 1、函数原型 #include <stdlib.h> void *malloc( size_t size ); v...

shzwork
12分钟前
3
0
什么是JavaBean? - What is a JavaBean exactly?

问题: I understood, I think, that a "Bean" is a Java class with properties and getters/setters. 我认为,“ Bean”是具有属性和getter / setter的Java类。 As much as I understand,......

技术盛宴
19分钟前
5
0
深圳援鄂最后一批工作人员归来,88万元关爱金发放至85人

中国公益在线3月31日深圳讯 深圳援鄂最后一批工作人员归来......深圳市民政局、深圳市卫健委和深圳市慈善会发起了“深爱战疫天使基金”项目,联合龙华区慈善会和 永贤慈善基金会,进行第二次...

传承天下融媒体中心
23分钟前
5
0
easyui 的combobox设置宽度和高度自动适应,如果超出,则指定宽度和高度

<s:select list="newCostTypeMap" theme="simple" cssClass="myCombobox" cssStyle="width:200px" data-options="editable:false,panelHeight:'auto'" />$('.myCombobox').combobox({......

文文1
24分钟前
5
0
Scala的运算符

在Scala中运算符的表示法不局限于字符, 中缀运算符可以是任何方法接受参数的方法 前缀运算符放在值的前面,只能是 + - ! ~ 四者之一, 方法名为unary_*(*为运算符) 后缀运算符是任何不接受参...

dreamness
33分钟前
17
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部