0

I can't load the data in controller, return undefined.

I have this factory service:

app.factory('factoryLlamada', function($http,$q) { return{
    cargar: function(archivo) {
        var deferred = $q.defer();
        $http.get(archivo).success(function(data) {
            deferred.resolve(data);
        })
        .error(function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }
}});

And this controller:

app.controller('ctrlProducts', function(factoryLlamada) {
    this.saludo = 'Hola'; //this work's
    factoryLlamada.cargar('prueba.json').then(function(data) {
        this.datos = data;
        console.dir(data);  //return json object (ok)
        console.dir(datos); //return undefined
    })
    .catch(function(error) {
        console.log('Se ha producido un error: '+error);
    });
});

I don't know which is the problem...

1 Answer 1

3

The this inside the callback function does not refer to the controller.

Write instead:

app.controller('ctrlProducts', function(factoryLlamada) {
    var vm = this;
    vm.saludo = 'Hola'; //this work's

    factoryLlamada.cargar('prueba.json').then(function(data) {
        vm.datos = data;
        console.dir(data);  //return json object (ok)
        console.dir(vm.datos);
    })
    .catch(function(error) {
        console.log('Se ha producido un error: '+error);
    });
});

And by the way, in the factory you don't have to use $q promises. Just reuse the promise returned by $http.get and the code will be much concise:

app.factory('factoryLlamada', function($http) { return{
    cargar: function(archivo) {
        return $http.get(archivo);
    }
}});

And retrieve the data like this:

factoryLlamada.cargar('prueba.json').then(function(response) {
    // data is in response.data
});
Sign up to request clarification or add additional context in comments.

3 Comments

That wont work since he states in the comments already this.saludo="Hola" works
The this from this.saludo refers to the controller as it's outside of the callback. But that's not the case for this.datos.
This answer is correct. You have to be careful using 'this' rather than $scope. In this case 'this' in the nested function is not the same as the 'this' in the controller.

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.