angularjs 處理多個異步請求方法匯總
在實際業(yè)務中經常需要等待幾個請求完成后再進行下一步操作。但angularjs中$http不支持同步的請求。
解決方法一:
$http.get('url1').success(function (d1) {
$http.get('url2').success(function (d2) {
//處理邏輯
});
});
解決方法二:
then中的方法會按順序執(zhí)行。
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方法第一個參數可以是數組(對象)。在第一參數中內容都執(zhí)行完后就會執(zhí)行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驗證信息框架的封裝插件用法【w5cValidator擴展插件】
這篇文章主要介紹了AngularJS驗證信息框架的封裝插件用法,分析了AngularJS表單驗證規(guī)則并實例說明了w5cValidator擴展插件的相關使用技巧,需要的朋友可以參考下2016-11-11
AngularJS基礎 ng-model-options 指令簡單示例
本文主要介紹AngularJS ng-model-options 指令,這里對ng-model-options指令的基本資料進行整理,有需要的小伙伴可以參考下2016-08-08
AngularJS基于ui-route實現深層路由的方法【路由嵌套】
這篇文章主要介紹了AngularJS基于ui-route實現深層路由的方法,涉及AngularJS路由嵌套操作相關實現步驟與技巧,需要的朋友可以參考下2016-12-12

