AngularJs: $http Synchronous call

孤者浪人 提交于 2020-01-29 13:19:25

问题


I have a service to for API call as following,

    getValue: function(input) {
        var deferred, url;
        deferred = $q.defer();
        url = "url";
        $http.post(url, input).success(function(data, status, headers, config) {
          return deferred.resolve({
            success: true,
            data: data,
            status: status,
            headers: headers,
            config: config
          });
        }).error(function(data, status, headers, config) {
          return deferred.resolve({
            success: false,
            data: data,
            status: status,
            headers: headers,
            config: config
          });
        });
        return deferred.promise;
      }

But this is async. How can I convert it to sync(I want to make it wait till I get the result)?


回答1:


No that is not possible with Angular.

See https://github.com/angular/angular.js/blob/master/src/ng/httpBackend.js#L51 where the XMLHttpRequest is opened with

xhr.open(method, url, true);

The third parameter in an xhr.open() can be set to false or true, where false is synchronous and true is asynchronous. In the Angular case, it is hardcoded to true, so that all outgoing calls will be asynchronous.

Use the .success() callback to wait until the async call returns, and then do whatever you want to do there.

As per the suggestion in the comments, you can of course also do the calls via raw javascript, jQuery or any other library that supports synchronous calls, but I would advise using callbacks/defers with the asynchronous angular call, because synchronous calls are blocking and blocking is bad.



来源:https://stackoverflow.com/questions/26603532/angularjs-http-synchronous-call

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