2013-04-14 4 views
4

데이터를 가져 오기 위해 $ http를 직접 호출하는 컨트롤러에 일부 코드가 있습니다. 이제 이것을 이것을 서비스로 옮기고 싶습니다. 여기에 지금까지 무엇을 가지고 :AngularJS의 서비스에서 약속을 어떻게 되돌릴 수 있습니까?

내 서비스 : 나는 다시 패스 성공의 결과를 전달하는 대신 때문에 오히려이를 변경할 수있는 방법

TestAccount.get(3, function (data) { 
     $scope.testAccounts = data; 
    }) 

: 컨트롤러 내부

angular.module('adminApp', []) 
.factory('TestAccount', function ($http) { 
    var TestAccount = {}; 
    TestAccount.get = function (applicationId, callback) { 
     $http({ 
      method: 'GET', 
      url: '/api/TestAccounts/GetSelect', 
      params: { applicationId: applicationId } 
     }).success(function (result) { 
      callback(result); 
     }); 
    }; 
    return TestAccount; 
}); 

성공했는지 실패했는지 확인할 수있는 약속을 되풀이합니까?

+0

는'$ http' 자체가 약속 때문에에'$ q' 약속 API에서 모든 방법을 사용할 수 있습니다 반환 , 또는'error' 콜백을 사용하십시오 – charlietfl

답변

3

서비스가 약속을 되찾아 서비스 클라이언트에 제공하십시오. 과 같이 서비스를 변경 :

angular.module('adminApp', []) 
.factory('TestAccount', function ($http) { 
    var TestAccount = {}; 
    TestAccount.get = function (applicationId) { 
     return $http({ 
      method: 'GET', 
      url: '/api/TestAccounts/GetSelect', 
      params: { applicationId: applicationId } 
     }); 
    }; 
    return TestAccount; 
}); 

그래서 컨트롤러에 당신이 할 수 있습니다

TestAccount.get(3).then(function(result) { 
    $scope.testAccounts = result.data; 
}, function (result) { 
    //error callback here... 
}); 
관련 문제