Use data returned by $ http in the AngularJS driver

1

My problem is that I make a request for $http to recover some data that I need to use in my controller, the problem is that if I make a console.log out with the variable assigned to the data it marks undefined .

I wanted to know if there is any way to use the data from that $scope without being within then of $http .

Example:

$http.get(config.root + 'index/trlang/'+lang).success(
    function(data){ $rootScope.trlang = data['lang'];}
);
console.log($rootScope.trlang); // undefined

This is when executing the controller, in the view the data is shown correctly, but in the controller I can not use that data since the requests are loaded in the last instance.

    
asked by Francisco Manuel Gonzalez Triv 14.01.2017 в 12:31
source

2 answers

1

Of course you can.

The simplest way to do this is to call a function when the HTTP request completes.

ejecutarEstaFuncion = function(data){
    // aqui puedes usar data como tu desees.
}


$http.get(config.root + 'index/trlang/'+lang).success(
   function(data){
      ejecutarEstaFuncion(data);
   }
);
    
answered by 15.01.2017 в 02:20
1

You can also do it before loading the driver, with the function resolve in ui-router as ngRoute , for example:

ui-router and / or ngRoute :

/*En ui-router*/
$stateProvider
    .state('exampleState', {
        url: '/exampleState',
        controller: "ExampleCtrl",
        resolve:{
            getData: function($q, $http){
                var deferred = $q.defer();
                $http.get(config.root + 'index/trlang/'+lang)
                    .success(function(data) {
                        return deferred.resolve(data);
                    })
                    .error(function(error, code) {
                        return deferred.reject(null);
                    }
                );
            }
        }
    }
)

/*En ngRoute*/
$routeProvider
    .when("/exampleState", {
        controller: "ExampleCtrl",
        resolve:{
            getData: function($q, $http){
                var deferred = $q.defer();
                $http.get(config.root + 'index/trlang/'+lang)
                    .success(function(data) {
                        return deferred.resolve(data);
                    })
                    .error(function(error, code) {
                        return deferred.reject(null);
                    }
                );
            }
        }
    }
)

In controller:

/*Controlador*/
angular.module("app")
    .controller("ExampleCtrl", function (getData) {
        console.log(getData);
    }
);
    
answered by 26.01.2017 в 04:23