angularjs链接承诺不起作用,angular.copy也不是

时间:2017-06-20 20:31:52

标签: javascript angularjs promise angular-promise

所以我的理解是我可以遍历我的FIRST返回的一组对象

对象= vm.liberty

循环

vm.liberty.forEach(function (obj) {

我对这个obj的理解是它是一个参考,因此vm.liberty对象会更新....对吗?

我知道console.log不可靠,因为它会在命中后立即吐出结果

然而

     console.log('obj', obj);

包含我想要的DATA,我已经在扩展的嵌套对象中添加了对象中的每个记录....

但有人要么我没有做正确的承诺链接还是别的什么

我甚至尝试做angular.copy

vm.liberty2 = angular.copy(vm.liberty);

这不起作用,因为console.log(vm.liberty);似乎是空的

这是我的功能:

    var loadLiberty = function () {

        var promise1 = libertyService.getLibertyQuestions();
        promise1.then(function (response) {
            vm.liberty = response;
        }).then(function (res) {
            vm.liberty.forEach(function (obj) {
                promise2 = libertyService.getDirectives(obj.QuestionId)
                    .then(function (result) {
                        obj.directives = result;
                        console.log('obj', obj);
                        //vm.liberty.directives = result;


                    }, function (err) {
                        console.log('err', err);
                    });

            });

        });
        //vm.liberty2 = angular.copy(vm.liberty);
        console.log(vm.liberty);
        vm.liberty2 = angular.copy(vm.liberty);
        //return promise1;
    };

想法或建议?

1 个答案:

答案 0 :(得分:0)

您的console.log(vm.liberty);在您的承诺得到解决之前发生,这就是为什么它仍然有其初始值。

看一下以下示例:

function loadLiberty() {

    const libertyQuestionsPromise = libertyService.getLibertyQuestions();

    libertyQuestionsPromise
        .then(x => vm.liberty = x)
        .then(() => {
            // hold promises which are getting directives in this array
            const promises = [];
            vm.liberty.forEach(obj => {
                // get directives for every obj
                const promise = libertyService
                    .getDirectives(obj.QuestionId)
                    .then(x => obj.directives = x);
                promises.push(promise);
            });
            // wait until all promises in the promises array are resolved
            return $q.all(promises);
        })
        .then(() => {
            // at this point the vm.liberty should be populated with results
            console.log(vm.liberty);
        })
        .catch(error => {
            // handle any error which might have occurred in any of the promises in this chain
        });

}

不要忘记在服务/控制器中注入$q依赖项。