angularjs处理多个$http

本文引自:https://www.cnblogs.com/xiaojikuaipao/p/6017899.html

在实际业务中经常需要等待几个请求完成后再进行下一步操作。但angularjs中$http不支持同步的请求。

解决方法一:

在第一请求完成后发起第二个请求

$http.get('url1').success(function (d1) {
  $http.get('url2').success(function (d2) {
     //处理逻辑
   });
});

解决方法二:

then中的方法会按顺序执行。这种方式称为链式调用,可解决多接口访问的问题,其中then方法中有三个参数,分别是成功回调、失败回调、状态变更回调,且只有前面的执行成功,后面的才会执行。

如果在某些场景中,等前一个方法调用完毕,而不管这个方法是否调用成功,都要继续调用后边的方法,则需要在then()方法中增加错误回调并return 下一个执行的promise。

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');
    },function(error){
     console.log(error); //打印第一个请求的错误信息
}); });

解决方法三:

$q.all方法可以把多个promise的数组合并成一个。当所有的promise执行成功后,会执行后面的回调,回调中的参数,是每个promise执行的结果。

其中方法参数可以是数组或json形式,依据参数形式决定回调结果是数组还是json形式。

而当all()方法的参数中存在一个promise失败,则整个任务都失败,返回的数据也只会返回该失败参数的失败信息。

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){  //arr为完成请求1和请求2后的返回值
        console.log(arr);
        angular.forEach(arr,function(d){
            console.log(d);
            console.log(d.data);
        })
    });
});

解决方法四:

when()方法中的参数可以是一个值,也可以是一个promise。

var val=10;
$q.when(val).then(function(success){
    console.log(success);
},function(err){
    console.log(err);
});
原文地址:https://www.cnblogs.com/x-jingxin/p/9811159.html