0

I need to retrieve xml data from local file.

With this simple code:

angular.module('exampleApp', [])
.controller('ExampleController', function($scope, $http) {

    var turniOra = this;

    $http.get("/XmlTemp/turni_giorno.xml",
        {
            transformResponse: function (cnv) {
                var x2js = new X2JS();
                var aftCnv = x2js.xml_str2json(cnv);
                return aftCnv;
            }
        })
        .then(
            function(datiConve){
                turniOra.prova = datiConve.data.turni.giornata;
            }
        );

    console.log(turniOra.prova); // undefined

});

The console log return "undefined", but with a $timeout directive:

$timeout(function() {
    console.log(turniOra.prova);
}, 50);

I have the correct object with xml data.

Why this happen, and how can I get the same result without $timeout?

Thanks

kecco
  • 196
  • 8

1 Answers1

1

It's normal.

Your request is done via AJAX. This seems that you request is asynchronous.

What does it mean ? Your requets is sent to the server and you're script continue to execute you're code without waiting the response from the server.

So in order you're code is doing that :

  • Sending http request
  • Log into console
  • Getting http response

But when you put a timeout, you already get http response before timeout's end.

You're solution would be to add your log into this function :

function(datiConve){
    turniOra.prova = datiConve.data.turni.giornata;
    console.log(turniOra.prova);
}

For more information about this in angular, take a look at angular promises

This is what $http used