AngularJs:$ HTTP同步调用 [英] AngularJs: $http Synchronous call

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

问题描述

我有一个服务,为API调用如下,

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)?

推荐答案

没有那是不可能的角度。

No that is not possible with Angular.

请参阅 https://github.com /angular/angular.js/blob/master/src/ng/httpBackend.js#L51 其中XMLHtt prequest打开与

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

在第三个参数的 xhr.open()可设置为真正,其中假是同步的,真正是异步的。在角的情况下,这是很难coded到真正,让所有拨出电话将是异步的。

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.

使用 .success()回调等待,直到异步调用返回,然后做任何你想做的事没有。

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

按照注释中的建议,你当然也可以做到通过原始的JavaScript,jQuery的或支持同步调用任何其他库的电话,但我会用回调建议/与异步角通话推迟,因为同步调用是阻止和拦截是坏的。

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.

这篇关于AngularJs:$ HTTP同步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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