0

我有一个返回值的 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");
}
4

2 回答 2

1

您正在addons从延迟函数中推送。

当你addons最后登录时,你还没有从你的addon_dependencies().then函数中推送。

您的函数应该看起来像 @sza 的代码!

于 2013-08-13T21:24:34.733 回答
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");
    });
}
于 2013-08-13T21:31:36.970 回答