angularjs 处理多个异步请求方法汇总
2015-01-06 08:59
666 查看
在实际业务中经常需要等待几个请求完成后再进行下一步操作。但angularjs中$http不支持同步的请求。
解决方法一:
复制代码 代码如下:$http.get('url1').success(function (d1) {
$http.get('url2').success(function (d2) {
//处理逻辑
});
});
解决方法二:
then中的方法会按顺序执行。
复制代码 代码如下:var app = angular.module('app',[]);
app.controller('promiseControl',function($scope,$q,$http) {
function getJson(url){
var deferred = $q.defer();
$http.get(url)
.success(function(d){
d = parseInt(d);
console.log(d);
deferred.resolve(d);
});
return deferred.promise;
}
getJson('json1.txt').then(function(){
return getJson('json2.txt');
}).then(function(){
return getJson('json1.txt');
}).then(function(){
return getJson('json2.txt');
}).then(function(d){
console.log('end');
});
});
解决方法三:
$q.all方法第一个参数可以是数组(对象)。在第一参数中内容都执行完后就会执行then中方法。第一个参数的方法的所有返回值会以数组(对象)的形式传入。
复制代码 代码如下:var app = angular.module('app',[]);
app.controller('promiseControl',function($scope,$q,$http) {
$q.all({first: $http.get('json1.txt'),second: $http.get('json2.txt')}).then(function(arr){
console.log(arr);
angular.forEach(arr,function(d){
console.log(d);
console.log(d.data);
})
});
});
$q的详细使用方法网上的有很多教程。我也是刚接触。讲不好,不敢乱讲。上面的代码是我按我的理解写的,经过了测试没有问题。
您可能感兴趣的文章:
相关文章推荐
- angularjs 处理多个异步请求方法汇总
- angularjs 处理多个异步请求方法汇总
- 转: angularjs 指令中动态编译的方法(适用于有异步请求的情况) 内嵌指令无效
- angularjs指令中动态编译的方法(适用于有异步请求的情况) 内嵌指令无效
- angularjs 指令中动态编译的方法(适用于有异步请求的情况) 内嵌指令无效
- 支付宝即时到账接口,异步回调post请求的接受,Jersey 处理post参数的方法
- Ajax请求二进制流进行处理(ajax异步下载文件)的简单方法
- Angularjs异步问题逻辑处理方法
- angularjs 指令中动态编译的方法(适用于有异步请求的情况) 内嵌指令无效
- Ajax请求二进制流进行处理(ajax异步下载文件)的简单方法
- AngularJS发送异步Get/Post请求方法
- 【C#】对异步请求处理程序IHttpAsyncHandler的理解和分享一个易用性封装 【手记】走近科学之为什么明明实现了IEnumerable<T>的类型却不能调用LINQ扩展方法 【手记】手机网页弹出层后屏蔽底层的滑动响应 【手记】ASP.NET提示“未能创建类型”处理 【Web】一个非常简单的移动web消息框 【手记】解决EXCEL跑SQL遇“查询无法运行或数据库表无法打开...”
- 使用angularjs异步请求数据(http请求或者使用Websocket)的时候,更新$scope中的dom的方法
- AngularJS出现$http异步后台无法获取请求参数问题的解决方法
- UTF-8异步请求到gbk应用的处理方法2
- SQL 2005 Report Server 请求因 HTTP 状态 400 失败: Bad Request 处理方法 的解决方法
- 下面的代码示例使用 BeginGetRequestStream 方法对流实例发出异步请求。
- 用.Net处理xmlHttp发送异步请求
- 异常处理方法,同步VS异步
- JAVA 中URL中文参数乱码的处理方法(汇总)