AngularJS: How to pass data outside a succes call

2019-08-10 00:41发布

问题:

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