我在这里看到一些混淆。我们试着清除它。如果您想使用延迟的对象,你需要改变你的代码位:
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
必须返回属于deferred
对象与return deferred.promise
的承诺。 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'承诺。不需要延期。 –
你有没有试过在'.then()'的成功和失败函数之外放置'return deferred.promise'? –
@MikeMcCaughan相同的值表示API响应与先前的API调用相同。 – Player