2016-12-27 90 views
0

我有一個angularfactory做一些$http與服務器的通信並返回一個字符串。但是,我得到Cannot read property 'then' of undefined錯誤。我讀了herehere,但遇到了類似的問題,但無法解決我的問題。

這是服務代碼:

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); 

    }); 

回答

2

您需要返回由$http即返回的承諾增加在$前面的http一個「迴歸」獲得您的代碼如下所示:

return $http(...) 
    .then(function successCallback(response) { 
     return response; 
    }, function errorCallback(response) { 
    }); 

這是因爲,t他從控制器調用的函數應該有一個.then方法,即它應該是一個承諾。 checkAvailability1在角度上返回一個承諾,需要由您的函數$http在工廠中返回。您只是從成功回調中返回了您的方法在控制器中不期望的響應。

+0

你能解釋一下這背後的邏輯嗎?我已經返回了對象本身和http請求的響應。 – undroid

+2

@undroid您正在從_callback method_返回該響應,而不是實際發出$ http請求的函數(checkAvailability1)。該結果永遠不會超出checkAvailability1的範圍。返回語句不會通過調用堆棧隱式「冒泡」。 –