2017-11-07 2 views
0

데이터를 반환하는 웹 서비스가 있습니다. 나는 각 서비스에 HTTP 요청 전화를 이동하려는 코드 중복을 방지하려면,다른 값으로 각도 약속 만들기

angular.module('abc', []) 
    .factory('def', function() { 
     return { 
      getData: function() { 
       return $http.post('/path/', {}); 
      } 
     }; 
    }); 

모두 훌륭하지만 필요한 데이터는 내부 객체를 복잡하고 나는 모든 시간을 쓸 필요가 :

def.getData().then(function (response) { 
    scope.obj = response.data.qwe.rty.xyz; 
}); 

무엇 response.data.qwe.rty.xyz의 가치를 successCallback으로 직접 전송하는 약속을 반환하는 가장 쉬운 방법은 무엇입니까? 그리고는 다음과 같이 쓸 수 있습니다 :

def.getData().then(function (obj) { 
    scope.obj = obj; 
}); 

답변

4

호출을 $http.post('/path/', {}) 돌아갑니다 다음 then()를 호출하는 약속을. then()도 약속을 반환하므로 통화를 연결할 수 있습니다. 코드는 그러므로 다음과 같을 수 있습니다 :

angular.module('abc', []) 
    .factory('def', function() { 
     return { 
      getData: function() { 
       return $http.post('/path/', {}) 
         .then(function(response) { 
          return response.data.qwe.rty.xyz; 
         }); 
      } 
     }; 
    }); 
2

당신이 $q 제공에 이렇게 같은

구현 된 연기 동작을 사용할 수 있습니다

angular.module('abc', []) 
.factory('def', function ($q) { 

    return { 
     getData: function() { 
      var def = $q.defer 
      $http.post('/path/', {}).then(function(response){ 
       def.resolve(response.data.qwe.rty.xyz) 
      }); 
      return def.promise; 
     } 
    }; 
}); 

와 같은 컨트롤러에서 사용 :

def.getData().then(function (response) { 
scope.obj = response; 
});