0

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.

1
  • 1
    getUser function must return a promise for .then in the controller to work. Commented Apr 5, 2016 at 10:42

2 Answers 2

1

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");
        }
    });
}; 
Sign up to request clarification or add additional context in comments.

Comments

0

Your getUser() function needs to return a promise:

var getUser = function(userId) {

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

You may need to pass resolve, reject into Restangulars promise

Comments

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.