Variable global angular problem

Asked

Viewed 3,665 times

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 a console.log(resultado), out of http it returns me Undefined, when one console.log() within http yet it returns me the correct result..

not with the url because it is from a client of mine.. but the url the return is ok, only when I pick off is not rolling the variable result.

Someone has a light?

  • 1

    Fluorescent or incandescent light?

  • The one that works kkkk

  • Got confused try to explain better

  • within $http, I store the date in the result variable, as access to the external result variable, outside of $http

2 answers

1


This happens because the $http executes an asynchronous request, then the resultado the moment you loga it has not been filled in yet. It will only be filled in after the request is finished and in your case if it is successful. Incidentally you should create a service to do this and not within the control, but this is another story.

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

It was clear?

Updating

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

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 much 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 in the scope the full service, which in turn returns a deferred. Also note that the controller no longer works with callback success but rather with the then, what is called precepts. The success and the error stay in service to be treated there. But the idea is the same, you have to continue your flow from the callback then.

Update 2

A better way to parse in this xml can be 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 has a cross-browser version (the above code probably won’t work in IE). And in this post has how to do in jQuery, which is much simpler.

  • It was not very clear, but what would be the correct way ? would be to create a service ? am I starting now with angular could give me an example please ? Hugs

  • 1

    @Lucasmoura I updated my answer. I hope I don’t complicate your life any further, but I’m also new to Angular and this example I’m using for my first project at my company. It would be nice if you told me how you use this result and how it is, so I can help you more.

  • Nice explanation Marty, see my brother... I do not know what would be this deferred and Promisses but I will research, vlw by Abraco explanation.. This result, I will play in slides, because it and a presentation screen of hotel suites... Another question... notice that I did to clean the return, because the return of my webservice brings me the json inside a <xml> that has a <string> here comes the json so this <xml><string>[{JSON}]</string></xml>, has some more practical way to clean this return ? This way was the one I did because I’m new at js, if I have a tmb light rsrs... hugs

  • 1

    @Lucasmoura updated again, with a more elegant way of treating your xml. Good luck guy!

  • 1

    Vlw, hugs...

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 am using this service ai... 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...

Because I need to do a setInterval, in which it will always be running the getResult service, if you have changed my webservice.. you understand ? vlw

  • Go to Edit and add your "other question" to the original question, specifying that it is a new doubt (do not delete the old one). So it’s easier to get an answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.