理解 AngularJS $q service and promises
来源:互联网 发布:手机淘宝怎么修改评价 编辑:程序博客网 时间:2024/06/06 00:19
Angularjs中的“$q”和 http访问的promises对象经常见到,本文主要介绍 AngularJS $q service and promises。
原文地址 http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/
介绍Angularjs $q service之前,我们需要了解promise是什么,它的作用是什么。
什么是promise
promise在JavaScript和angularjs中,是指我们通过执行某个动作(如:click button)后,在将来某个时间点返回数据的对象。让我们看以下两种情况。
- promise被填充——通过执行某个动作后,返回的数据填充到promise对象中(意味着我们获取到了response,不管这个response的结果是成功或者是失败)。
- promise被拒绝——通过执行某个动作后,不能获取到response(例如通过访问API获取服务器数据,但是服务器一直不能返回数据)。
为什么需要promise
我们需要promise是因为需要根据返回的结果(或者不返回结果)做出决定,下面的用一个例子说明。
我们的程序通过访问服务器API获取客户列表。
如果获取到response返回数据后,将数据显示到屏幕中;
如果不能获取到response返回数据时,提示用户。
使用$q service 处理promise
angularjs中提供了$q 处理异步请求并且可以获得API的返回值。其真正出彩的地方是用户可以自定义promise。
看一个简单的例子。
var deferred = $q.defer();// deferred 中包含了带有返回值的promise// 解析带有返回值的promise使用.resolvedeferred.resolve(data);// 解析被拒绝的promise 使用 .rejectdeferred.reject(error);现在,看一下angularjs如何具体实现。
app.service("githubService", function ($http, $q) { var deferred = $q.defer(); this.getAccount = function () { return $http.get('https://api.github.com/users/haroldrv') .then(function (response) { // promise is fulfilled deferred.resolve(response.data); // promise is returned return deferred.promise; }, function (response) { // the following line rejects the promise deferred.reject(response); // promise is returned return deferred.promise; }) ; };});最终,angularjs controller中使用该service并且显示结果或提示用户数据不能返回。
app.controller("promiseController", function ($scope, $q, githubService) { githubService.getAccount() .then( function (result) { // promise was fullfilled (regardless of outcome) // checks for information will be peformed here $scope.account = result; }, function (error) { // handle errors here console.log(error.statusText); } );});
阅读全文
0 0
- 理解 AngularJS $q service and promises
- “JavaScript Promises和AngularJS $q Service”Part 1 (基础篇)
- “JavaScript Promises和AngularJS $q Service”Part 2 (教程篇)
- “JavaScript Promises和AngularJS $q Service”Part 1 (基础篇)
- AngularJS 用promises和$q处理异步调用
- angularJS $q and promise
- Using AngularJS Promises
- angularJS的service理解
- Dojo Deferreds and Promises
- angularJs-The factory and service of angularJs
- 理解ES6: Promises
- 理解AngularJS中的Service类型
- 理解AngularJS中的Service类型
- 理解AngularJS中的Service类型
- angularjs速成学习个人理解_6$q服务的promise
- Promises
- NodeJS Multiple Callback解决之使用Q Promises
- promises/A+协议的实现模块【q】使用心得
- addpath用法小结
- GBDT梯度提升树算法原理小结(三)
- 复杂数据及运算
- RecyclerView的使用
- 常用正则
- 理解 AngularJS $q service and promises
- hdu1532 Drainage Ditches(入门) [最大流]
- php基础知识 11,php中的session
- POI操作Excel常用方法总结
- 谷歌浏览器设置在新标签页打开连接而不是覆盖当前页
- 群硕20170515Java研发实习生笔试题
- NIO学习
- 离散题目3
- .Net Warning 合集