1

introduction: I have a problem return value in $http method, i understand how to works $http in $http.post and $http.get method, i can't return value outside the function that call to my factory.

i need use $scope.historias value outside the controller function.

My Angular Factory: First Factory:

mediperbaricaApp.factory('listarTratamientos',['$http','$location','$q', 
                                                function($http, $location, $q){
    var urlBase = host + 'index.php/';
    var service = {};
    console.log('DEBUG = entramos');

    return {
        response : function(response){
            return $http({
                url : (urlBase + 'tratamientos/getTratamientos'),
                method : 'GET' 
            })
        }
    }

}]);

second Factory:

mediperbaricaApp.factory('services', [ '$http' ,'$location', function(
                                                    $http, $location){
  var urlBase = host + 'index.php/';
  var service = {};
  //listado de historias para el autocoplete del form
  service.getHistorias = function(callback){
    console.log('[DEBUG] FAC Listar Historias');
    $http.get(urlBase + 'historias/getHistoria').
    success(function(response){
        return callback(response);
    }).
    error(function(response){
        alert('Lo sentimos!, No se puede recuperar los datos, ' +
                                                      ' intente mas tarde :(');
    })
  };

  return service;
}]);

My Angular Controller Controller, using two last factories, i get same result

mediperbaricaApp.controller('editController',function($scope,listarTratamientos,
                                         $location,$routeParams, services){
    console.log('[DEBUG] CTRL editar tratamientos');
    //use first factory
    $scope.datos = {};
    services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
    })
    //the data no exist in this place.
    console.dir($scope.datos); //$scope.datos lost data :(

    //use second factory
    $scope.midata = {};
    listarTratamientos.response().success(function(data){
        $scope.midata = data;
        console.dir($scope.midata);  // output array with data :)
    });
    //data not exist in this place i dont understand
    console.dir($scope.midata); //$scope.datos lost data :(

Thanks your help!. Att. Eduardo

2
  • the data is there, but you are misinterpreting the results. console.log (or .dir) is executed immediately, it doesn't wait for a promise to be fulfilled. Once the promise finishes, the data will be there, but it's not there when you execute the command. Commented Jul 27, 2015 at 22:28
  • you are trying to log the data to console before it has been returned from server...you can't do that. Ajax is asynchronous Commented Jul 27, 2015 at 22:28

1 Answer 1

1

So in this part you have a callback function and you're trying to access the value in the code below it:

services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
    })
    //the data no exist in this place.
    console.dir($scope.datos); //$scope.datos lost data output undefined variable :(

The problem is that the callback function is executed slightly after this code block, so everything you do with that data needs to be called from within that callback, for example:

services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
        myFunction();
    })
...

function myFunction() {
    console.dir($scope.datos); //$scope.datos now available :)
}

The same goes for your other block of code.

Remember this about the callback/async functions: just because a line of code is right below another line of code - it doesn't mean they will execute in that order.


I'll show you two super-simple examples now - a wrong one (like you did), and a good one, using setTimeout to simulate an async call:

The wrong one

var data;

setTimeout(function() {
  data = 'I will not be available!';
}, 100);

alert(data); // undefined


The right one

var data;

setTimeout(function() {
  data = 'Que suerte!';
  showAlert();
}, 100);

function showAlert(){
  alert(data); // all good!
}

Sign up to request clarification or add additional context in comments.

4 Comments

thanks!! function myFunction(){ console.dir($scope.datos); //with data } console.dir($scope.datos); //without data ; :(
You're welcome! Yes, the trick is to call all the code that requires datos once the data is ready, and that's what that function call does. Here's an interesting link about that: callbackhell.com This is good also: recurial.com/programming/…
Thanks friend XD, javascript it's complicated every day I understand a little more the language
No problem. Every start is complicated, but keep working on it and you'll become good at it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.