使用AngularJS中的Factory,在第一次完成后使用不同的参数调用相同的$ http函数

时间:2016-09-27 06:16:55

标签: javascript angularjs

myDatamyFactory中生成,如果myData函数生成myHttp.GetGroupMember,则以下代码有效。

但是,当它们“同时”执行时,它无法处理多个GetGroupMember个调用,dataContainer会从createMyData调用初始化。

首先GetGroupMember“完成”后,如何拨打第二个GetGroupMember

var myFactory = function (myHttp) {

    var myData = [];
    var dataContainer = [];
    var numProgress;

    var onSuccess = function(data_member) {
        myData.push(data_member);
        numProgress++;
        loadMember(dataContainer); // if member is succefully loaded, load next member
        // if numProgress == data_member.length, call next GetGroupMember() here?
    }

    var loadMember = function(data_group) {
        if (numProgress < data_group.length) {
            myHttp.getMemberDetails(data_group.division, data_group.members[numProgress]).then(onSuccess, onError);
        }
    }

    var createMyData = function(response) {
        dataContainer = response; // coded as shown to call loadMember() iteratively
        loadMember(dataContainer);
    }

    var getMyData = function(init) {
        myHttp.getGroupMember("Division1", "Group_Foo").success(createMyData); // getGroupMember_1
        // how to call getGroupMember_2 after getGroupMember "finished"?
        myHttp.getGroupMember("Division2", "Group_Bar").success(createMyData); // getGroupMember_2

        return myData;
    }
}

var myControl = function($scope, myFactory) {

    $scope.myData = myFactory.getMyData();
}

1 个答案:

答案 0 :(得分:1)

世界上最简单的事情:

myHttp.getGroupMember("Division1", "Group_Foo")
.success(createMyData)
.then(function() {
     return myHttp.getGroupMember("Division2", "Group_Bar")
}).success(createMyData); 

阅读promises