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

查看:26
本文介绍了如何等到响应来自 $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?

推荐答案

对于不知道何时完成的异步操作,您应该使用 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)

一个示例实现如下:

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() 调用在 .then() 函数完成执行之前不会返回.

Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

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 秒才能完成.如果该函数在那段时间内没有返回任何内容,它将有效地成为正常的同步代码,并会挂起浏览器,直到它完成.

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.

虽然承诺立即返回,但浏览器可以在此期间自由地继续处理其他代码.一旦承诺解决/失败,则触发 then() 调用.因此,这种方式更有意义,即使它可能会使您的代码流更复杂一些(毕竟,复杂性毕竟是异步/并行编程的常见问题!)

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天全站免登陆