AngularJS Ajax Call in Service

£可爱£侵袭症+ 提交于 2019-12-11 09:53:24

问题


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)

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;
    });
};
}]);

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

The new service looks like this:

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);
};

[...]

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?


回答1:


the ajax/http class are asynchronous... ajax itself means aysnc. read this article

so the code keep executing next par and dont wait for the response...




回答2:


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

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



来源:https://stackoverflow.com/questions/25020367/angularjs-ajax-call-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!