2014-07-25 22 views
0

在我的全局/主控制器中,我加载了几个ngResources。我如何暂停执行其他任何事情直到加载?类似于路线的解析属性。控制器内的角度解决方案

// The "global" controller in which I perform one time on load actions. 
app.controller('FrontendCtrl', function($scope, authService, sessionService) { 

    // Here I check if the user has a cookie and if so fetch info from server to reinit session 
    authService.updateUser(); 

    $scope.$session = sessionService; 

}); 

// Auth service 
app.factory('authService', function($q, Auth, Other, sessionService) { 

    // Populate local user data from server - one query followed by a few subsequent ones - all are ngResources 
    var updateUser = function() { 
     Auth.profile(null, function(data) { 
     if(data) { 
      $q.all({ 
      foo: Other.foo({ user_id: data.id }), 
      bar: Other.bar({ user_id: data.id }), 
      }) 
      .then(function(results) { 
      sessionService.user = _.merge(results, data); 
      }); 
     } 
     }); 
    }; 
}); 

// In my view - this doesn't work if there is a delay in loading the updateUser function 
{{ $session.user.name }} 
+1

为什么不让服务返回您在控制器中用来填充会话的承诺? – Edminsson

+0

@ Edminsson +1,这是最好的方式,在我做之前先用完整的答案来开发它。 – coma

+0

@coma,继续我的朋友,发展成为一个完整的答案。 – Edminsson

回答

0

你需要利用回调的序,让服务先找来填充会话值,这里是你的代码:

// Auth service 
app.factory('authService', function($q, Auth, Other) { 

    // Populate local user data from server - one query followed by a few subsequent ones - all are ngResources 
    return { 
     updateUser: function(callback) { 
     Auth.profile(null, function(data) { 
      if(data) { 
      $q.all({ 
       foo: Other.foo({ user_id: data.id }), 
       bar: Other.bar({ user_id: data.id }), 
      }) 
      .then(function(results) { 
       //If sessionService is only an object in this case 
       callback(sessionService); 
      }); 
      } 
     }); 
     }; 
    } 

}); 

,并在控制器:

// The "global" controller in which I perform one time on load actions. 
app.controller('FrontendCtrl', function($scope, authService) { 

    // Here I check if the user has a cookie and if so fetch info from server to reinit session 
    //Update: Now a callback to fetch session data 
    authService.updateUser(function(data){ 
    $scope.$session = data; 
    }); 
}); 
+0

之前调用then(),我最终使用了promise,但是这也适用,所以我会将其标记为答案。 – cyberwombat