AngularJS Ajax 调用服务 [英] AngularJS Ajax Call in Service

查看:24
本文介绍了AngularJS Ajax 调用服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序对 RESTful Web 服务进行 Ajax 调用.在我的 html 文档中有两个连接到范围对象的文本框.这两个字段都通过 ng-change 连接到post"功能.post 方法将form"变量从作用域发送到 API,Web 服务将这两个数字相加并以 json 文件进行响应,该文件现在包含结果.(这可能不是很 RESTful,但它对我有用)

I want my application to make Ajax Calls to a RESTful Webservice. In my html document are two textboxes that are connected to a scope object. Both fields are connected to the "post" function via ng-change. The post method sends the "form" variable from the scope to the API and the webservice adds both numbers and responds with a json file, which now contains the result. (This might not be very RESTful but it works for me)

只要我的控制器中有这样的 Ajax 调用,它就可以正常工作:

It works perfectly fine as long as I have the Ajax call in my controller like this:

myApp.controller('myCtrl', ['$scope', '$http', function ($scope, $http) {

$scope.form = {
    "number1" : "",
    "number2" : "",
    "result"  : ""
};


$scope.post = function () {
    $http({
        url: "http://localhost:7777/api",
        method: "POST",
        data: $scope.form,
        headers: {'Content-Type': 'application/json'}
    }).success(function (data, status, headers, config) {
        $scope.form = data;
    }).error(function (data, status, headers, config) {
        $scope.status = status;
    });
};
}]);

当然,这看起来不太好.所以我试着把 Ajax 调用放到一个服务中.

Now of course that does not look very nice. So I tried to put the Ajax call into a service.

新服务如下所示:

myApp.service('myService', ['$http', function ($http) {
      this.post = function (scopeData) {

        var myData = scopeData;

        alert('Result1: ' + myData.result);

        $http({
                url: "http://localhost:7777/api",
                method: "POST",
                data: myData,
                headers: {'Content-Type': 'application/json'}
            }).success(function (data, status, headers, config) {
                myData = data;
                alert('Result2: ' + myData.result);
            }).error(function (data, status, headers, config) {
                var status = status;
            });
        };

        alert('Result3: ' + myData.result);

        return myData;

      };
    }]);

在控制器中,我这样调用服务:

In the controller I call the service like this:

[...]

$scope.post = function($scope.form) {
    $scope.form = myService.post($scope.form);
};

[...]

它根本不起作用.所以我在服务中添加了这三个警报.当我在浏览器中打开我的应用程序时发生的情况是,当我更改一个字段时,弹出的第一个警报是名为Result1"的警报,然后是Result3",然后是Result2".Result2 甚至显示正确的结果.所以不知何故,我的服务中的发布"功能似乎没有等待 ajax 调用完成.

It didn't work at all. So I added those three alerts in the service. What happens when I open my app in a browser is that when I change a field, the first alert that pops up is the one called "Result1", then "Result3" and then "Result2". Result2 even shows the correct result. So somehow it seems like the "post" function in my service does not wait for the ajax call to finish.

有人知道我该如何解决这个问题吗?

Does anybody know how I might fix this?

推荐答案

这里的问题是您正在处理异步进程.alert('Result3: ' + myData.result); 将在 alert('Result2: ' + myData.result); 之前发生,因为 http GET 将要需要更长的时间.我最好的建议是通过创建 angularjs 来查看这个 stackoverflow 问题和响应

The problem here is that you are dealing with async processes. alert('Result3: ' + myData.result); is going to happen before alert('Result2: ' + myData.result); because the http GET is going to take longer. My best advice is to see this stackoverflow question and response by the create of angularjs

此外,如果您正在使用 RESTful 服务,请考虑查看 ngResource.它将极大地简化您的代码.

Also, if you are working with RESTful services, consider looking at ngResource. It will simplify your code tremendously.

这篇关于AngularJS Ajax 调用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆