从 Angular 数据工厂中的 HTTP POST 请求接收未定义的结果

Receiving an undefined result from an HTTP POST Request in an Angular DataFactory

本文关键字:请求 结果 未定义 POST HTTP Angular 数据 工厂      更新时间:2023-09-26

我是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>

我得到的错误是在行数据工厂.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。

有以下几种方法:

then(successCallback, errorCallback, notifyCallback) – 无论承诺何时被解析或拒绝,一旦结果可用,就会异步调用其中一个成功或错误回调。使用单个参数调用回调:结果或拒绝原因。此外,在解决或拒绝承诺之前,可以调用零次或多次通知回调以提供进度指示。

此方法返回一个新的承诺,该承诺通过 successCallback 的返回值 errorCallback 解析或拒绝(除非该值是承诺,在这种情况下,它使用使用该承诺链接在该承诺中解析的值进行解析)。它还通过 notifyCallback 方法的返回值进行通知。无法从 notifyCallback 方法解析或拒绝承诺。

catch(errorCallback) – promise.then(null, errorCallback) 的简写

final(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({ 之间的中断导致错误。所以它需要看起来像这样:

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({...})