Global angular variable problem

0
app.controller('controllerPrincipal', function($scope, $http){


        var resultado;
        $http({method: 'GET', params: {id: 2}, url: 'url'}).success(function(data)
        {
            // limpando o retorno
            var p = data.search("{")-1;
            var res = data.substring(76);
            var f = res.search('<');
            dados = data.substring(p, p+f);
            resultado = JSON.parse(dados);
        });

        console.log(resultado);


});

When I give console.log(resultado) , out of http it returns me undefined, when from a console.log() inside http it still returns me the correct result ..

Does anyone have a LIGHT?

    
asked by anonymous 31.03.2014 / 22:15

2 answers

1

This happens because $http executes an asynchronous request, so resultado at the moment you loga has not been populated yet. It will only be populated once the request ends and in your case if it is successful. By the way you should create a service to do this and not within control, but that is another story.

For you to use this data, wherever you are using it, you have to continue within success . For example: If you use this in a third-party lib, you have to call it in there, or in any function, passing that result.

Is it clear?

Update

In your case, to include a service you can use factory or service , both providers . This example uses the first one:

app.factory('controllerPrincipalService', function($http, $q) {
    return {
            getResultado: function(id) 
            {
                var deferred = $q.defer();

                $http(
                {
                    method: 'GET', 
                    url: 'url',
                    data: {id:id}
                }).success(function(data, status, headers, config) 
                {
                    deferred.resolve(data);
                }).error(function(data, status, headers, config) 
                {
                    deferred.reject(status);
                });

                return deferred.promise;
            }
        };
});

So you separate the layers and leave the requests outside the controller, which makes your code more organized. Your controller would look like this:

app.controller('controllerPrincipal', ["$scope", "controllerPrincipalService", function($scope, $http) {
    controllerPrincipalService.getResultado(id).then(function(dados)
    {
        // limpando o retorno
        var p = data.search("{")-1;
        var res = data.substring(76);
        var f = res.search('<');
        dados = data.substring(p, p+f);
        resultado = JSON.parse(dados);
    });
}]);

Note the dependency injection that the controller has ["$scope", "controllerPrincipalService" . This gives you the full service scope, which in turn returns a deferred . Note also that the controller now no longer works with the callback success but with then , which is called promisses . The success and error are in the service to be dealt with there. But the idea is the same, you have to continue your flow from the callback then .

Update 2

A better way to parse into this xml might look like this:

xmlparser = new DOMParser();
xmlDoc = xmlparser.parseFromString(dados, "text/xml");
var string = xmlDoc.getElementsByTagName("string")[0].innerHTML;
var json = JSON.parse(string);

In this article you have a cross-browser version (the above code is probably will not work in IE). And in this post can do in jQuery, which is much simpler.

    
31.03.2014 / 23:07
0

Another doubt Marcio ..

 controllerPrincipalService.getResultado(id).then(function(dados)
    {
        // limpando o retorno
        var p = data.search("{")-1;
        var res = data.substring(76);
        var f = res.search('<');
        dados = data.substring(p, p+f);
        resultado = JSON.parse(dados);
    });

For example I'm using this service there ... beauty ... if I need to use the result elsewhere, for example a function below that service within the control would be possible?

Example;

 controllerPrincipalService.getResultado(id).then(function(dados)
    {
        // limpando o retorno
        var p = data.search("{")-1;
        var res = data.substring(76);
        var f = res.search('<');
        dados = data.substring(p, p+f);
        resultado = JSON.parse(dados);
    });

    function pegaResultado(resultado){
        ///trabalhar com o resultado do service a cima.
        console.log(resultado);

    }

Why this ...

I need to do a setInterval, in which it will always be running the service getResultado, if it has alteration in my webservice .. understood? vlw

    
01.04.2014 / 18:35