2014-04-08 2 views
0

services.js 행 :방법 컨트롤러 동기 호출하여 AngularJS와

mPortalServices.factory('ChannelTypeService', ['$filter', '$http', '$q', function (filter, $http, $q) { 
    var ChannelTypeService = {}; 
    ChannelTypeService.getAll = function() { 
     var defered = $q.defer(); 
     $http.get('jsondata/ChannelType.json').then(function(response){ 
      defered.resolve(response.data); 
     }); 
     return defered.promise; 
    } 
    ChannelTypeService.getSingle2 = function (typeId) { 
     var defered = $q.defer(); 
     ChannelTypeService.getAll().then(function(items){ 
      var filtered = filter('filter')(items, { 
       'TypeId': typeId 
      }); 
      defered.resolve(filtered); 
     }); 
     return defered.promise; 
    } 

    return ChannelTypeService; 
}]); 

controllers.js :

//some code here... 
var firstChannel = channels[0]; 

ChannelTypeService.getSingle2(firstChannel.ChannelType).then(
    function(activities) { 
     $scope.channelType = activities; 
     console.log('1111'); 
     console.log($scope.channelType); 
    } , 
    function(reason) { } 
); 
console.log("2222"); 
console.log($scope.channelType); 
if ($scope.channelType.Type == 1) { 
    $location.path("/list1/"); 
} 
else { 
    $location.path("/list2/"); 
} 
return; 

난 getSingle2 함수의 결과를 기다려야 할하지만 위의 코드 방법, 비동기 질문을 해결 하시겠습니까?

+0

코드가 작동하지 않는 방법은 무엇입니까? – Sprottenwels

+0

먼저 코드 인쇄 1111 및 정의되지 않은 및 인쇄 2222 및 개체, 채널 유형 값을 원한다면 뒤에 문을 – Net205

+0

네이티브 솔루션이 것 같습니다. http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs : 당신은 [1] [1] [답]를 읽을 수 있습니다 – Aray

답변

0

변경에 controllers.js 다음

function someFunction() { 
    //some code here... 
    var deferred = $q.defer(); 

    var firstChannel = channels[0]; 

    ChannelTypeService.getSingle2(firstChannel.ChannelType).then(
     function(activities) { 
      $scope.channelType = activities; 
      console.log('1111'); 
      console.log($scope.channelType); 

      console.log("2222"); 
      console.log($scope.channelType); 

      // the following code will now work: 
      deferred.resolve(); 
      if ($scope.channelType.Type == 1) { 
       $location.path("/list1/"); 
      } 
      else { 
       $location.path("/list2/"); 
      } 

     } , 
     function(reason) { } 
); 

    return deferred.promise; 
} 

해야 할 것 위의 함수의 결과를 필요로하는 코드 : 당신이 강제 할 경우,

someFunction.then(function() { 
    // guaranteed to run after, for example, $scope.channelType has been set 
}) 

Net205 말했듯을 getSingle2를 동기식으로 사용하면 일반적으로 그렇게 할 수 없습니다.