如何使用 AngularJS 进行 $http 同步调用 [英] How to $http Synchronous call with AngularJS

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

问题描述

有什么办法可以用 AngularJS 进行同步调用吗?

Is there any way to make a synchronous call with AngularJS?

AngularJS 文档不是很明确,也不是很广泛,无法弄清楚一些基本的东西.

The AngularJS documentation is not very explicit or extensive for figuring out some basic stuff.

服务:

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

推荐答案

目前没有.如果您查看源代码(来自this时间点 2012 年 10 月),您会看到对 XHR open 的调用实际上是硬编码为异步的(第三个参数为真):

Not currently. If you look at the source code (from this point in time Oct 2012), 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);

您需要编写自己的服务来进行同步调用.通常,这不是您通常想要做的事情,因为 JavaScript 执行的性质最终会阻塞其他一切.

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.

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

... 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.

除此之外,如果您要自己动手,请了解有关如何进行同步和异步 ajax 调用的更多信息 可以在这里找到.

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.

希望对您有所帮助.

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

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