使用依赖于先前资源调用的promise来链接资源异步调用

时间:2014-12-10 03:08:45

标签: angularjs chaining angular-promise ngresource

我在链接依赖于先前变量的资源调用时遇到问题,下面是代码。测试变量返回一个对象,该对象包含我想用来调用另一个资源的authorityId属性,并将返回值添加到通过test返回的对象。似乎我不能让它与推迟正常工作,请建议一个正确的方法,并解释它,以便我可以完全掌握这个概念。

test will return {   
Key : [{ properties: somethingSomething, properties2: somethingSomething, 
         properties3:somethingSomething}]
}



(function (angular) {
'use strict';
angular.module('module.userManagement')
    .factory('userService', ['userCtrlService','authoritiesService','$q',function     (userCtrlService,authoritiesService,$q) {

        var test = $q.all({'getAdminRole' : authoritiesService.getAdministrator().$promise,'getUserRole': authoritiesService.getUserRole().$promise}).then(function(results){
                        var deferred = $q.defer();
                        var resourceList = [];
                        angular.forEach(results,function(value,key){
                           value.$promise.then(function(response){
                               angular.forEach(response, function(v,k){
                                  resourceList.push(v);
                               });
                           });
                        });
                       deferred.resolve(resourceList);
                       return deferred.promise;
                    });

        console.log('USER SERVICE!');

 test.then(function(response){
          var authorityList = {};
          var deferred = $q.defer();
          angular.forEach(response, function(resValue,key){
            authoritiesService.getAuthenticationAssignment({id:resValue.authorityId}).$promise.then(function(response){
                var className = {};
                if(response[resValue.authorityId][0]) {
                    className['className'] = response[resValue.authorityId][0].className;
                    className['singular'] = response[resValue.authorityId][0].singular;
                }
               authorityList[resValue.name] = [{'description': resValue.description, 'authorityId': resValue.authorityId, 'category': resValue.authorityCategoryName, 'level':className}];
            });
          });
          deferred.resolve(authorityList);

          console.log(authorityList);
        });

0 个答案:

没有答案