簡體   English   中英

Angular-無法從工廠接收$ http響應

[英]Angular - Having troubles receiving $http response from a factory

我有一個angular factory正在與服務器進行一些$http通信並返回一個字符串。 但是我得到了Cannot read property 'then' of undefined錯誤的Cannot read property 'then' of undefined 在這里這里閱讀時遇到類似的問題,但是無法解決我的問題。

這是服務代碼:

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返回的promise,即在$ http前面添加“ return”,以使您的代碼像下面這樣工作:

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

這是因為,您從控制器調用的函數應該在其上帶有.then方法,即應為promise。 checkAvailability1中的checkAvailability1返回一個checkAvailability1 ,工廠中的函數$http需要返回一個checkAvailability1 您只是從成功回調返回響應,這是控制器中的方法所不希望的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM