Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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中的方法会按顺序执行。

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‘,$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);
        })
    });
});

解决方法四:

var app = angular.module(‘app‘,[]);
app.controller(‘directiveControl‘,$http,$q){
    function getTxt(a) {
        var deferred = $q.defer();
        $http.get(‘1.json‘)
            .success(function (d) {
                console.log(a);
                deferred.resolve();
            })

        return deferred.promise;
    }
    getTxt(1).then(function(){
        return getTxt(2);
    }).then(function(){
        return getTxt(3);
    }).then(function(){
        return getTxt(4);
    }).then(function(){
        return getTxt(5);
    }).then(function(){
        console.log(‘end‘);
    });
});

大佬总结

以上是大佬教程为你收集整理的angularjs处理多个$http全部内容,希望文章能够帮你解决angularjs处理多个$http所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。