2017-03-09 1 views
0

API에서 데이터를 가져 오는 서비스가 있습니다.이 서비스를 호출하려고합니다. 같은 가치로 돌아오고 있습니다.defer.promise가 angularJS에서 동일한 결과를 반환합니다.

appName.service('FetchCustomerDate', ['$http', '$q', function($http, $q) { 
    var self = this; 
    self.getCustomerData = function(token,name) { 
     var deferred = $q.defer(); 
     return $http({ 
      method: 'GET', 
      url: , 
      headers: { 
       "Authorization": token, 
       "x-xcmc-auth": '' 
      } 
     }).then(function(response) { 
      deferred.resolve(response); 
      return deferred.promise; 
     }, function(response) { 
      deferred.reject(response); 
      return deferred.promise; 
     }); 
    }; 
}]); 
+3

"같은 값"은 무엇을 의미 하는가를? 바로 지금,'return deferred.promise' 줄은 아무 것도하지 않습니다; 그냥'$ http' 약속을 반환하십시오. 지연에 대한 필요가 없습니다. –

+0

당신은'return deferred.promise;'행을'.then()'의 성공과 실패 함수 외부에 넣으려고 했습니까? –

+0

@MikeMcCaughan 동일한 값은 API 응답이 이전 API 호출과 동일 함을 의미합니다. – Player

답변

0

여기에 약간의 혼란이 있습니다. 그것을 지우려고 노력합시다. 당신이 지연된 객체를 사용하려는 경우, 당신은 당신의 코드를 약간 수정해야합니다

상세
appName.service('FetchCustomerDate', ['$http', '$q', function ($http, $q) { 
    var self = this; 
    self.getCustomerData = function (token, name) { 
     var deferred = $q.defer(); 
     $http({ // Do not return here, you need to return the deferred.promise 
      method: 'GET', 
      url: '...some URL here...', 
      headers: { 
       "Authorization": token, 
       "x-xcmc-auth": '' 
      } 
     }).then(function (response) { 
      deferred.resolve(response); // It's correct, you are resolving the deferred promise here. 
      // return deferred.promise; // You do not need to return the deferred.promise here. 
     }, function (response) { 
      deferred.reject(response); // It's correct, you are rejecting the deferred promise here. 
      // return deferred.promise; // You do not need to return the deferred.promise here. 
     }); 

     return deferred.promise; // The function must return the deferred.promise 
    }; 
}]); 

이 기능 getCustomerDatareturn deferred.promisedeferred 객체에 속하는 약속을 반환해야합니다. then() 콜백 내에서 deferred 약속을 해결하거나 거부하면됩니다. deferred.promise을 반환 할 필요가 없습니다.

코드를 개선 할 수 있습니다. $http 서비스는 약속을 반환하며 then 콜백에 의해 반환 된 값은 약속에서 then 메서드로 래핑됩니다. 당신이 deferred 객체의 사용을 제거 할 수 있음을 알고이 이유로, 당신이 볼 수 있듯이

appName.service('FetchCustomerDate', ['$http', function ($http) { 
    var self = this; 
    self.getCustomerData = function (token, name) { 
     return $http({ // Here, you need to return the promise returned by $http. Than promise will contain the response returned inside "then" callbacks. 
      method: 'GET', 
      url: '...some URL here...', 
      headers: { 
       "Authorization": token, 
       "x-xcmc-auth": '' 
      } 
     }).then(function (response) { 
      return response; // Simply return the response, it will be wrapped in a resolved promise by "then()" 
     }, function (response) { 
      return response; // Simply return the response, it will be wrapped in a rejected promise by "then()" 
     }); 
    }; 
}]); 

가, 2 then 콜백 단순히 response 객체를 반환하면이를 생략 할 수 있습니다 : 보통

appName.service('FetchCustomerDate', ['$http', function ($http) { 
    var self = this; 
    self.getCustomerData = function (token, name) { 
     return $http({ // Here, you need to return the promise returned by $http. Than promise will contain the response form the GET call 
      method: 'GET', 
      url: '...some URL here...', 
      headers: { 
       "Authorization": token, 
       "x-xcmc-auth": '' 
      } 
     }); 
    }; 
}]); 
+0

정말 감사합니다. – Player

0

$http 서비스로 데이터를 가져 오는 경우 응답에서 데이터를 가져와 $scope에 영향을 주거나 어떻게 든 처리해야합니다. 너 뭐하려고? 귀하의 질문을 명확히하십시오.

일반적으로이 같은 모양 가져 오기 :

appName.service('FetchCustomerDate', ['$http', '$q', function($http, $q) { 
    var self = this; 

    function notifyError(reason) { 
     console.error(reason); 
    } 

    self.getCustomerData = function(token,name) { 
     var deferred = $q.defer(); 
     return $http({ 
      method: 'GET', 
      url: , 
      headers: { 
       "Authorization": token, 
       "x-xcmc-auth": '' 
      } 
     }) 
      .then(function onSuccess(response) { 
      var cfg = response.data; // process data 
     }) 
      .then(function onSuccess(response) { 
      // chained promises 
     }) 
      .then(
      function onSuccess(res) { 
       // ... this will trigger the chain reaction 
       deferred.resolve(res); 
      }, 
      function onFailure(reason) { 
       notifyError(reason); // manage the error 
       deferred.reject(reason); 
      }) 
      ; 
      return deferred.promise; 
     } 
    }]); 
관련 문제