0
我有一個angular
factory
做一些$http
與服務器的通信並返回一個字符串。但是,我得到Cannot read property 'then' of undefined
錯誤。我讀了here和here,但遇到了類似的問題,但無法解決我的問題。
這是服務代碼:
factory("availabilityService", ['$http', function ($http) {
return {
checkAvailability1: function (element, string) {
// ..... some object creation code ......
$http({
method: 'POST',
url: 'server/server.php',
data: AvailableObj,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function successCallback(response) {
return response;
}, function errorCallback(response) {
});
}
}
}]);
裏面一個controller
:
$scope.checkAvailability = function (element, string) {
availabilityService.checkAvailability1(element, string).then(function (response) { //on this line the error occurs
console.log(response);
});
你能解釋一下這背後的邏輯嗎?我已經返回了對象本身和http請求的響應。 – undroid
@undroid您正在從_callback method_返回該響應,而不是實際發出$ http請求的函數(checkAvailability1)。該結果永遠不會超出checkAvailability1的範圍。返回語句不會通過調用堆棧隱式「冒泡」。 –