值返回并推送到数组中但在返回时不可用

时间:2013-08-13 21:21:22

标签: javascript arrays angularjs

我有一个返回值的Angular服务。我将该值推送到数组,console.log显示该值确实被推送。但在此回调之外,数组不显示推送值。如何使用推送值保存此数组?

$scope.setAddons = function() {
var addons = new Array();
var arr = filterFilter($scope.addons, {checked: true});
    for (var i = 0; i < arr.length; i++) {          
        element = arr[i].addoncode;
        addons.push(element);
        console.log(addons); // ["A6004"] great!
    }           
    for (var x = 0; x < addons.length; x++) {                   
        var dep = '';
        myService.addon_dependencies(addons[x]).then(function(dependency) {
        dep = dependency[0].addon_depend;
        console.log(dep); // A6002
            if(dep != null){
                addons.push(dep);
                console.log(addons); // ["A6004", "A6002"] great!
            }
        });
    }
    myService.addItem('addons', addons); //saving ["A6004"] instead of ["A6004", "A6002"]
    console.log(addons); // ["A6004"] just shoot me!
    location.path("/rates");
}

2 个答案:

答案 0 :(得分:1)

您将从延迟函数中推送到addons

当您在结尾处记录addons时,尚未从addon_dependencies().then功能中推送。

你的功能应该像@sza的代码一样!

答案 1 :(得分:1)

您应该使用$q.all 同步 执行 所有 服务调用,如下所示:

(抱歉,我无法测试你的代码,但是你应该能够自己调试。希望它可以解释一下。)

$scope.setAddons = function () {
    var addons = new Array();
    var arr = filterFilter($scope.addons, {
        checked: true
    });
    for (var i = 0; i < arr.length; i++) {
        element = arr[i].addoncode;
        addons.push(element);
        console.log(addons); // ["A6004"] great!
    }

    var queries = [];
    for (var x = 0; x < addons.length; x++) {
        queries.push(myService.addon_dependencies(addons[x]));
    }

    $q.all(queries).then(function (data) {
        for (var x = 0; x < addons.length; x++) {
            var dep = dependency[x].addon_depend;
            console.log(dep); // A6002
            if (dep != null) {
                addons.push(dep);
                console.log(addons); // ["A6004", "A6002"] great!
            }
        }

        myService.addItem('addons', addons); //saving ["A6004"] instead of ["A6004", "A6002"]
        console.log(addons); // ["A6004"] just shoot me!
        location.path("/rates");
    });
}