如何等到响应来自$ http请求,在angularjs? [英] How to wait till the response comes from the $http request, in angularjs?

查看:217
本文介绍了如何等到响应来自$ http请求,在angularjs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的一些数据,它是由多个页面的RESTful服务。
所以我使用该角度工厂。所以,我需要从服务器获取一次数据,每次和我正在与定义服务的数据。就像一个全局变量。下面是示例:

I am using some data which is from a RESTful service in multiple pages. So I am using angular factories for that. So, I required to get the data once from the server, and everytime I am getting the data with that defined service. Just like a global variables. Here is the sample:

var myApp =  angular.module('myservices', []);

myApp.factory('myService', function($http) {
    $http({method:"GET", url:"/my/url"}).success(function(result){
        return result;
    });
});

在我的控制器中我使用此服务:

In my controller I am using this service as:

function myFunction($scope, myService) {
    $scope.data = myService;
    console.log("data.name"+$scope.data.name);
}

其工作正常,我按我的要求。
但这里的问题是,当我在我的网页重新加载该服务将被再次调用和服务器的请求。如果在之间的一些其他功能执行这依赖于定义的服务,它使象东西的误差是不确定的。所以,我想在我的剧本要等到该服务被加载。我该怎么办呢?反正有这样做,在angularjs?

Its working fine for me as per my requirements. But the problem here is, when I reloaded in my webpage the service will gets called again and requests for server. If in between some other function executes which is dependent on the "defined service", It's giving the error like "something" is undefined. So I want to wait in my script till the service is loaded. How can I do that? Is there anyway do that in angularjs?

推荐答案

您应该使用异步操作的承诺,你不知道什么时候会完成。一诺再presents一个尚未完成的操作,但在未来的预期。 (<一href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise\">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

这是示例实现是这样的:

An example implementation would be like:

myApp.factory('myService', function($http) {

    var getData = function() {

        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){

            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };


    return { getData: getData };
});


function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  

       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}

编辑:关于Sujoys评论说,
什么我需要做的,这样myFuction()调用不会返回到。那么()函数执行完毕。

function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }

好吧,让我们假设在调用的getData()用了10秒的时间完成。如果函数没有在那个时候返回任何东西,这将有效地成为正常同步code和会挂起浏览器,直到它完成。

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

随着承诺立即返回不过,浏览器是免费的,继续与在此期间,其他code。一旦该承诺解析/失败了,则()调用被触发。因此,它更有道理这样一来,即使它可能使你的$ C $的流动℃的稍微复杂(复杂性是一般毕竟异步/并行编程的通病!)

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

这篇关于如何等到响应来自$ http请求,在angularjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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