여기에 약간의 혼란이 있습니다. 그것을 지우려고 노력합시다. 당신이 지연된 객체를 사용하려는 경우, 당신은 당신의 코드를 약간 수정해야합니다
상세
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
};
}]);
이 기능 getCustomerData
가 return deferred.promise
와 deferred
객체에 속하는 약속을 반환해야합니다. 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": ''
}
});
};
}]);
"같은 값"은 무엇을 의미 하는가를? 바로 지금,'return deferred.promise' 줄은 아무 것도하지 않습니다; 그냥'$ http' 약속을 반환하십시오. 지연에 대한 필요가 없습니다. –
당신은'return deferred.promise;'행을'.then()'의 성공과 실패 함수 외부에 넣으려고 했습니까? –
@MikeMcCaughan 동일한 값은 API 응답이 이전 API 호출과 동일 함을 의미합니다. – Player