angularJS中的同步http调用 [英] synchronous http call in angularJS

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

问题描述

我有以下情况,我需要来自特定网址的数据。我写了一个带参数'url'的函数。在函数内部,我有$ http.get方法,它调用url。数据将返回到调用函数

I have the following scenario, I need data from a particular url. I have written a function which takes parameter 'url'. Inside the function I have the $http.get method which makes a call to the url. The data is to be returned to the calling function

var getData = function (url) {
    var data = "";

    $http.get(url)
        .success( function(response, status, headers, config) {
             data = response;
        })
        .error(function(errResp) {
             console.log("error fetching url");
        });
    return data;
}

问题如下,$ http.get是异步的,在响应之前获取后,函数返回。因此,调用函数将数据作为空字符串获取。在从网址中提取数据之前,如何强制该函数不返回?

The problem is as follows, $http.get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string. How do I force the function not to return until the data has been fetched from the url?

推荐答案

看看承诺克服这些问题,因为它们在角落世界中被广泛使用。

Take a look at promises to overcome such issues, because they are used all over the place, in angular world.

你需要使用 $ q

var getData = function (url) {
    var data = "";
    var deferred = $q.defer();

    $http.get(url)
        .success( function(response, status, headers, config) {
             deferred.resolve(response);
        })
        .error(function(errResp) {
             deferred.reject({ message: "Really bad" });
        });
    return deferred.promise;
}

这是关于 promises and $ q

更新:

FYI, $ http 服务本身返回一个承诺,所以 $ q 在这种情况下不一定是必需的(因此反模式

FYI, $http service itself returns a promise, so $q is not necessarily required in this scenario(and hence an anti-pattern).

但是不要让这个成为跳过阅读关于$ q和承诺的理由。

But do not let this be the reason to skip reading about $q and promises.

所以上面的代码相当于以下内容:

So the above code is equivalent to following:

var getData = function (url) {
    var data = "";
    return $http.get(url);
}

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

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