如何使用AngularJS进行$ http同步调用

Fla*_*ira 131 http angularjs

对不起,我的新手问题,但AngularJS文档不是非常明确或广泛,以找出一些基本的东西.

有没有办法与AngularJS进行同步调用?

在服务上:

myService.getByID = function (id) {
    var retval = null;

    $http({
        url: "/CO/api/products/" + id,
        method: "GET"
    }).success(function (data, status, headers, config) {

        retval = data.Data;

    });

    return retval;
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*esh 112

不是现在.如果查看源代码(从2012年10月的时间点开始),您将看到对XHR open的调用实际上是硬编码为异步(第三个参数为true):

 xhr.open(method, url, true);
Run Code Online (Sandbox Code Playgroud)

您需要编写自己的同步调用服务.一般情况下,由于JavaScript执行的性质,您通常不会想要这样做,因此最终会阻止其他所有内容.

...但是......如果实际上需要阻止其他所有内容,也许你应该查看promises和$ q服务.它允许您等待一组异步操作完成,然后在它们全部完成后执行.我不知道你的用例是什么,但这可能值得一看.

除此之外,如果您打算自己动手,可以在此处找到有关如何进行同步和异步ajax调用的更多信息.

我希望这是有帮助的.

  • 你可以请代码片段来实现使用$ q服务.我尝试了很多选项,但它以异步方式工作. (12认同)
  • 以下视频帮助我学习了承诺[AngularJS Promises with $ q](https://www.youtube.com/watch?v=cdG_T6ufcbE) (3认同)
  • @Venkat:我知道这是一个迟到的回复,但正如我在回答中所说的那样,调用将永远是"异步"你只需要使用$ q使其等待*等待响应,然后继续你的逻辑内部`.then(回调)`.类似于:`doSomething(); $ http.get( '/ A /事情'),那么(doEverythingElse);`. (2认同)

all*_*lel 12

我曾与一家工厂集成谷歌地图自动完成和承诺,我希望你服务.

http://jsfiddle.net/the_pianist2/vL9nkfe3/1/

您只需要在出厂前用$ http incuida替换此请求的autocompleteService.

app.factory('Autocomplete', function($q, $http) {
Run Code Online (Sandbox Code Playgroud)

和$ http请求

 var deferred = $q.defer();
 $http.get('urlExample').
success(function(data, status, headers, config) {
     deferred.resolve(data);
}).
error(function(data, status, headers, config) {
     deferred.reject(status);
});
 return deferred.promise;

<div ng-app="myApp">
  <div ng-controller="myController">
  <input type="text" ng-model="search"></input>
  <div class="bs-example">
     <table class="table" >
        <thead>
           <tr>
              <th>#</th>
              <th>Description</th>
           </tr>
        </thead>
        <tbody>
           <tr ng-repeat="direction in directions">
              <td>{{$index}}</td>
              <td>{{direction.description}}</td>
           </tr>
        </tbody>
     </table>
  </div>

'use strict';
 var app = angular.module('myApp', []);

  app.factory('Autocomplete', function($q) {
    var get = function(search) {
    var deferred = $q.defer();
    var autocompleteService = new google.maps.places.AutocompleteService();
    autocompleteService.getPlacePredictions({
        input: search,
        types: ['geocode'],
        componentRestrictions: {
            country: 'ES'
        }
    }, function(predictions, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            deferred.resolve(predictions);
        } else {
            deferred.reject(status);
        }
    });
    return deferred.promise;
};

return {
    get: get
};
});

app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
    var promesa = Autocomplete.get(newValue);
    promesa.then(function(value) {
        $scope.directions = value;
    }, function(reason) {
        $scope.error = reason;
    });
 });

});
Run Code Online (Sandbox Code Playgroud)

问题本身就是:

deferred.resolve(varResult); 
Run Code Online (Sandbox Code Playgroud)

当你做得很好并且请求时:

deferred.reject(error); 
Run Code Online (Sandbox Code Playgroud)

当出现错误时,然后:

return deferred.promise;
Run Code Online (Sandbox Code Playgroud)


小智 5

var EmployeeController = ["$scope", "EmployeeService",
        function ($scope, EmployeeService) {
            $scope.Employee = {};
            $scope.Save = function (Employee) {                
                if ($scope.EmployeeForm.$valid) {
                    EmployeeService
                        .Save(Employee)
                        .then(function (response) {
                            if (response.HasError) {
                                $scope.HasError = response.HasError;
                                $scope.ErrorMessage = response.ResponseMessage;
                            } else {

                            }
                        })
                        .catch(function (response) {

                        });
                }
            }
        }]


var EmployeeService = ["$http", "$q",
            function ($http, $q) {
                var self = this;

                self.Save = function (employee) {
                    var deferred = $q.defer();                
                    $http
                        .post("/api/EmployeeApi/Create", angular.toJson(employee))
                        .success(function (response, status, headers, config) {
                            deferred.resolve(response, status, headers, config);
                        })
                        .error(function (response, status, headers, config) {
                            deferred.reject(response, status, headers, config);
                        });

                    return deferred.promise;
                };
Run Code Online (Sandbox Code Playgroud)