Shaikh Saleem
Shaikh Saleem

Reputation: 75

ngresource factory returns undefined

Am writing a factory with ngresource and although it prints the value in success callback it doesn't return the value back to the controller. I receive Undefined in the console.

.controller('loginCtrl', function($scope,loginInfoService) {
console.log(loginInfoService.getJsonId());
})

.factory('accessUrlService', ['$resource',function($resource){
return $resource('ip/Web/ws/login/restLogin');
}])


.factory('loginInfoService', ['accessUrlService',function(accessUrlService){

return  {
    getJsonId: function() {         
                accessUrlService.save({"login":"admin","password":"log","role":"Admin"},function(data){
                console.log(data.jsessionId);                           
                return data;                                
                });     
            }
        }

}])

Upvotes: 1

Views: 85

Answers (2)

Denis
Denis

Reputation: 747

I think you should try to declare a return statement in your getJsonId method

getJsonId: function() {         
                return accessUrlService.save({"login":"admin","password":"log","role":"Admin"},function(data){
                console.log(data.jsessionId);                           
                return data;                                
                });     
            }

And in your controller call this method like

loginInfoService.getJsonId().$promise.then(function(response){ console.log(response); });

Upvotes: 0

Shaikh Saleem
Shaikh Saleem

Reputation: 75

I had to use $q service here. I passed $q as parameter to my factory and then deferred the response until I received a response from the server.

This is the modified factory

.factory('loginInfoService',['accessUrlService','$q',function(accessUrlService,$q){
  return  {
getJsonId: function() {  
    var deferred = $q.defer();
      accessUrlService.save({"login":"admin","password":"log","role":"Admin"},function(data){
       deferred.resolve(data); 
    },function(error){
        console.log("eror");
        deferred.reject(error);
    }); 

    return deferred.promise;
    }
}
}])

And I call it in the controller like this.

.controller('loginCtrl', function($scope,loginInfoService) {
  loginInfoService.getJsonId().then(function(data){
console.log(data.jsessionId);
  },function(error){
console.log(error+ " Error" )
  });
})

Do let me know if I can impove upon this code.

Upvotes: 0

Related Questions