简体   繁体   中英

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

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.

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");
        }
    });
}; 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM