2014-07-25 2 views
0

내 전역/주 컨트롤러에서 몇 개의 ngResources를로드합니다. 적재 될 때까지 어떻게 다른 작업을 일시 중지 할 수 있습니까? 라우트의 resolve 특성과 유사합니다.컨트롤러 내의 각도 분해

// 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

당신은 서비스가 세션 값을 채우는 첫 놓아 inorder를 콜백의 사용을 만들 필요, 여기 당신을위한 코드입니다

// 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

나는 약속을 사용하는 것을 끝내었다. 그러나 이것은 내가 대답으로 표시 할 정도로 잘 작동한다. – cyberwombat