AngularJS and Restangular: TypeError: Cannot read property 'then' of undefined

Issue

I built a service and this service return an object. But, in my controller i don’t work with this object because ‘.then’ dont’t work.

My service:

var getUser = function(userId) {

    Restangular.all(userId).post(JSON.stringify()).then(function(response) {
        var obj = angular.fromJson(response);
        if (!obj.isError) {
            return obj;
        }
        else {
            console.log("ERRO getUserCard");
        }
    });
};

My controller:

var succsess = function(data){
    welcomeScope.getUser = data;
    console.log("getUser: " + welcomeScope.getUser);
};

var error = function(){
    console.log("Erro error");
};

function loadProfile(){ 
    welcomeSvc.getUser("203831").then(success,error);
};

Note: welcomeScope is my $scope.

Solution

you should add return in function getUser

var getUser = function(userId){
   return Restangular.all(userId).post(JSON.stringify()).then(function(response){
        var obj = angular.fromJson(response);
        if (!obj.isError) {
            return obj;
        }
        else{
            console.log("ERRO getUserCard");
        }
    });
}; 

Answered By – small fish

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.