如何使用$ resource基于_.each迭代以角度等待多个请求

时间:2016-02-02 08:37:04

标签: angularjs angular-resource

您好我有一个基于_.each迭代执行多个请求的方法。我想要做的是在_.each迭代后的vm.job = job中初始化getAllJobSublinesByJobline

    var vm = this;

    function getAllJobSublinesByJobline () {
        return $resource( '/api/joblines/get_all_jobsublines_by_jobline/:pageLimit', {
            'jobLineId' : '@jobLineId',
            'page'      : '@page',
            'search'    : '@search',
            'sortField' : '@sortField',
            'sortType'  : '@sortType'
        } );
    }

    function getJobsublinesByJoblineId ( joblines, job ) {
        _.each( joblines, function ( jobline ) {
            if ( parseInt( jobline.num_sublines ) ) {
                var jobsublineFetchDetails = {
                    'pageLimit' : 10,
                    'jobLineId' : jobline.id
                };
                return getAllJobSublinesByJobline().save( jobsublineFetchDetails ).$promise.then( function ( jobsubline ) {
                    jobline.jobsublines = jobsubline.data;
                    job.joblines.push( jobline );
                } );
            }
            job.joblines.push( jobline );
        } );
        vm.job = job; // initializes right away even though _.each iteration is not finished yet
    }

我的问题是,即使_.each迭代尚未完成获取数据,它也会立即初始化。为什么会这样?

3 个答案:

答案 0 :(得分:0)

您可以将所有承诺推送到数组并使用类似

的内容
$q.all(yourPromises).then(function(allCompletedResponse){...}).

答案 1 :(得分:0)

来自文档:

  

重要的是要意识到调用$resource对象方法会立即返回一个空引用(对象或数组,具体取决于isArray)。从服务器返回数据后,将使用实际数据填充现有引用。

- AngularJS $resource API Reference

正如在另一个答案中所说,推送承诺,并使用$q.all

function getJobsublinesByJoblineId ( joblines, job ) {
    var promises = [];
    _.each( joblines, function ( jobline ) {
        if ( parseInt( jobline.num_sublines ) ) {
            var jobParams = {
                'pageLimit' : 10,
                'jobLineId' : jobline.id
            };
            var details = getAllJobSublinesByJobline().save( jobParams );
            promises.push(details.$promise);
        }
    } );
    $q.all(promises).then (function (detailsArray) {
         //assemble job object
         vm.job = job;
    });
}

答案 2 :(得分:0)

由于我需要初始化有关jobubline的职位,我所做的与上面的答案类似。

    function getJobsublinesByJoblineId ( joblines, job ) {
        var promises = _.map( joblines, function ( jobline ) {
            var jobParams = {
                'jobLineId' : jobline.id
            };

            var deferred = $q.defer();

            apiService.getAllJobSublinesByJobline().save( jobParams ).$promise.then( function ( jobsubline ) {
                jobline.jobsublines = jobsubline.data;
                deferred.resolve( jobline );
            } );

            return deferred.promise;
        } );

        $q.all( promises ).then( function ( joblines ) {
            job.joblines = joblines
            vm.job       = job;
        } );
    }