簡體   English   中英

從Angular DataFactory中的HTTP POST請求接收未定義的結果

[英]Receiving an undefined result from an HTTP POST Request in an Angular DataFactory

我是Angular.js的新手,並嘗試使用工廠通過http post請求發送數據。 我收到此錯誤Cannot read property 'success' of undefined這里是我的代碼...

<!DOCTYPE html>
<html ng-app="myApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>
    <div ng-controller="myCtrl">

    </div>

    <script>
        var app = angular.module('myApp', []);

        app.factory('DataFactory', ['$http', function($http) {
            return {
                setData: function(stud) {
                    return
                    $http({
                        method: 'POST',
                        url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        data: stud
                    });

                }
            }

        }]);

        app.controller('myCtrl', function($scope, DataFactory) {

            var stud = {
                name: "Alex",
                city: "Berlin"
            };


            DataFactory.setData(stud).then(function(response) {
                    console.log(response);
                })
                .catch(function(err) {
                    console.error(err)
                })
                .finally(function() {
                    console.log("Finished the chain");
                });
        });
    </script>

</body>

</html>

我得到的錯誤是在線DataFactory.setData(stud).success ...任何幫助非常感謝...

所以文檔說:

var promise = someAsyncMethodCall();
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
});

看到底部,有2個函數傳遞給then函數。 所以你的代碼是:

DataFactory.setData(stud).then(function(response) {
     console.log(response);
}, function (err) {
     console.error(err)
});

$ q庫是$ http引用的內容。

看到承諾api

有這些方法:

然后(successCallback,errorCallback,notifyCallback) - 無論何時或將要解決或拒絕承諾,只要結果可用,就會異步調用其中一個成功或錯誤回調。 使用單個參數調用回調:結果或拒絕原因。 另外,在解決或拒絕承諾之前,可以將通知回調調用零次或多次以提供進度指示。

此方法返回一個新的promise,它通過successCallback的返回值errorCallback解析或拒絕(除非該值是一個promise,在這種情況下,它使用promise鏈接解析該值中的值)。 它還通過notifyCallback方法的返回值進行通知。 無法從notifyCallback方法解析或拒絕承諾。

catch(errorCallback) - promise.then的簡寫(null,errorCallback)

finally(callback,notifyCallback) - 允許您觀察承諾的履行或拒絕,但是這樣做而不修改最終值。 無論承諾被拒絕還是已解決,這對於釋放資源或進行必要的清理都非常有用。 有關更多信息,請參閱完整規范。

因此,為了進一步提高代碼,您可以:

DataFactory.setData(stud).then(function(response) {
    console.log(response);
})
.catch(function (err) {
    console.error(err)
})
.finally(function () {
    console.log("Finished the chain");
});

---編輯---

為了完整起見,@ Duncan說了另一個錯誤,那就是換行符:

app.factory('DataFactory', ['$http', function($http) {
    return {
        setData: function(stud) {
            return
            $http({
                method: 'POST',
                url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: stud
            });

        }
    }

}]);

return$http({之間的中斷$http({導致錯誤。所以它需要看起來像這樣:

app.factory('DataFactory', ['$http', function($http) {
    return {
        setData: function(stud) {
            return $http({
                method: 'POST',
                url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: stud
            });

        }
    }

}]);

$http返回一個Promise 你需要使用.then()來注冊成功的回調。

更一般的形式是.then(successFn, failFn)

你的問題在函數setData()

                return
                $http({
                    method: 'POST',
                    url: 'http://www.w3schools.com/jquery/demo_test_post.asp',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: stud
                });

這是兩個語句: return只是從函數返回,然后對$http()的調用是永遠不會達到的附加代碼。

小心你在Javascript中放置換行符,移動$http({到上一行。

哦,正如其他人所說,不推薦使用$http調用結果的.success ,轉而使用普通的promise方法。

它只是降價還是在返回和$ http之間有換行符? 如果你返回那里,$ http就無法訪問。 函數可以低於返回值,因為它們是在代碼執行之前注冊的。

所以你應該寫它

return $http({...})

代替

return $http({...})

暫無
暫無

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

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