AngularJS: How to pass data outside a succes call in $http.get

こ雲淡風輕ζ 提交于 2019-12-11 10:06:52

问题


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;

});


回答1:


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


来源:https://stackoverflow.com/questions/33981636/angularjs-how-to-pass-data-outside-a-succes-call-in-http-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!