简体   繁体   English

从Angular DataFactory中的HTTP POST请求接收未定义的结果

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

I am new to Angular.js and trying to use factory for sending data via http post request. 我是Angular.js的新手,并尝试使用工厂通过http post请求发送数据。 I am getting this error Cannot read property 'success' of undefined here is my code... 我收到此错误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>

The error I am getting is at line DataFactory.setData(stud).success... any help much appreciated... 我得到的错误是在线DataFactory.setData(stud).success ...任何帮助非常感谢...

So the docs state: 所以文档说:

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

See the bottom, there are 2 functions to pass to the then function. 看到底部,有2个函数传递给then函数。 So your code is: 所以你的代码是:

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

The $q library is what $http uses under the hood. $ q库是$ http引用的内容。

See the promise api . 看到承诺api

There are these methods: 有这些方法:

then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. 然后(successCallback,errorCallback,notifyCallback) - 无论何时或将要解决或拒绝承诺,只要结果可用,就会异步调用其中一个成功或错误回调。 The callbacks are called with a single argument: the result or rejection reason. 使用单个参数调用回调:结果或拒绝原因。 Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. 另外,在解决或拒绝承诺之前,可以将通知回调调用零次或多次以提供进度指示。

This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining). 此方法返回一个新的promise,它通过successCallback的返回值errorCallback解析或拒绝(除非该值是一个promise,在这种情况下,它使用promise链接解析该值中的值)。 It also notifies via the return value of the notifyCallback method. 它还通过notifyCallback方法的返回值进行通知。 The promise cannot be resolved or rejected from the notifyCallback method. 无法从notifyCallback方法解析或拒绝承诺。

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

finally(callback, notifyCallback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. finally(callback,notifyCallback) - 允许您观察承诺的履行或拒绝,但是这样做而不修改最终值。 This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. 无论承诺被拒绝还是已解决,这对于释放资源或进行必要的清理都非常有用。 See the full specification for more information. 有关更多信息,请参阅完整规范。

So to further your code, you could do: 因此,为了进一步提高代码,您可以:

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

--- EDIT --- ---编辑---

For completeness, there was another error that @Duncan said, that is the line break: 为了完整起见,@ 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
            });

        }
    }

}]);

The break between return and $http({ is causing an error. So it needs to look like this: 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 returns a Promise . $http返回一个Promise you need to use .then() to register a callback on success. 你需要使用.then()来注册成功的回调。

The more general form is .then(successFn, failFn) 更一般的形式是.then(successFn, failFn)

Your problem is in the function setData() : 你的问题在函数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
                });

That is two statements: return just returns from the function, then the call to $http() is additional code that is never reached. 这是两个语句: return只是从函数返回,然后对$http()的调用是永远不会达到的附加代码。

Be careful where you put line breaks in Javascript, move the $http({ up to the previous line. 小心你在Javascript中放置换行符,移动$http({到上一行。

Oh, and as others have said, using .success on the result from $http calls is deprecated, switch to using the normal promise methods instead. 哦,正如其他人所说,不推荐使用$http调用结果的.success ,转而使用普通的promise方法。

Is it just markdown or do you have a newline between return and $http? 它只是降价还是在返回和$ http之间有换行符? If you return there, $http becomes unreachable. 如果你返回那里,$ http就无法访问。 Functions can be below the return, since they are registered before code execution. 函数可以低于返回值,因为它们是在代码执行之前注册的。

So you should write it like 所以你应该写它

return $http({...})

instead of 代替

return $http({...})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM