AngularJS:如何在$ http.get中的成功调用之外传递数据 [英] AngularJS: How to pass data outside a succes call in $http.get

查看:167
本文介绍了AngularJS:如何在$ http.get中的成功调用之外传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular中,我创建了一个服务来从json文件(在我的代码:file4.json中)用$ http.get调用检索数据。
在成功调用中,数据被传递到数组'bmlService.items'中。 console.log显示事情进展顺利。
但是,该数组在$ http.get函数外是空的。
如何将数据传递到此函数之外?

这是我的代码:

<$ p $ ($ http){
var bmlService = {};

bmlService.items = []; $ b $ app.service('bmlService' b
$ http.get(file4.json)

.success(函数(数据){
bmlService.items =数据;

console.log(inside succes call:,bmlService.items);
})

.error(function(data,status){
alert(出错了...);
});

console.log(outside http.get:,bmlService.items);

return bmlService;

});

解决方案


然而,这个数组在$ http.get函数之外是空的。如何将数据传递到此函数之外?

您不能这样做,因为AJAX调用是异步的,并且此数据仅在回调后才可用已经执行 - 这可能会在发起AJAX调用之后的较晚阶段发生。因此,如果您想将它传递到外部,您可以调用其他函数并将数据作为参数传递给此函数:

  .success(function(data){
bmlService.passData(data);
})


$ b $因此,基本上你必须重新设计你的代码来处理回调,而不是一些依次分配的顺序调用和变量:

  var bmlService = {
passData:function(data){
//对这里的数据做些什么
}
};


In Angular I've made a service to retrieve data with a $http.get call from a json file (in my code: file4.json). In the success call the data is passed into the array 'bmlService.items'. The console.log shows things went well. However, this array is empty outside the $http.get function. How can I pass the data outside this function?

This is my code:

app.service('bmlService', function($http){
var bmlService = {};

bmlService.items = [];

    $http.get("file4.json")

        .success(function(data){
            bmlService.items = data;

            console.log("inside succes call: ", bmlService.items);
            })

        .error(function(data, status){
            alert("Something went wrong...");
        });

        console.log("outside http.get: ", bmlService.items);

return bmlService;

});

解决方案

However, this array is empty outside the $http.get function. How can I pass the data outside this function?

You cannot because the AJAX call is asynchronous and this data is available only after the callback has executed - which can happen at a much later stage after firing the AJAX call. So if you want to pass it to the outside you could invoke some other function and pass the data as parameter to this function:

.success(function(data) {
    bmlService.passData(data);
})

So basically you will have to redesign your code to work with callbacks instead of some sequential calls and variables that get assigned one after the other:

var bmlService = {
    passData: function(data) {
        // do something with the data here
    }
};

这篇关于AngularJS:如何在$ http.get中的成功调用之外传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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