如何美元,AngularJS HTTP同步调用 [英] How to $http Synchronous call with AngularJS

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

问题描述

我的新手问题抱歉,但angularjs文档也不是很明确的广阔的,有人推测基本的东西。

是否有某种方式,使同一个angularjs电话synchromous?

上的服务:

  myService.getByID =功能(ID){
    VAR RETVAL = NULL;    $ HTTP({
        URL:/ CO / API /产品/+ ID,
        方法:GET
    })。成功(功能(数据,状态,头,配置){        RETVAL =数据。数据;    });    返回RETVAL;
}


解决方案

当前未。如果你看看源$ C ​​$ C (行56个大气压),你会看到调用XHR开放实际上是硬coded到是异步的(第三个参数为true):

  xhr.open(方法,URL,真正的);

您就需要编写自己的服务,做到同步调用。普遍认为不是你通常会想,因为JavaScript执行你最终阻止一切的性质做。

...但..如果阻止一切实际上是希望,也许你应该看看承诺和 $ Q服务。它可以让你等到了一套异步操作完成后,再执行一次东西他们都完成了。我不知道你的使用情况是什么,但可能是值得一试。

以外的是,如果你打算推出自己的,更多的信息,如何同步和异步AJAX调用<一个href=\"https://developer.mozilla.org/en-US/docs/DOM/XMLHtt$p$pquest/Synchronous_and_Asynchronous_Requests\">can在这里找到。

我希望这是有帮助的。

sorry for my newbie question, but angularjs documentation is not very explicit or extensive as for someone figure basic stuff.

Is there some way to make a synchromous call with angularjs?

ON A SERVICE:

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

解决方案

Not currently. If you look at the source code (line 56 atm), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

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

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