ngresource工厂返回undefined

时间:2016-03-01 19:21:53

标签: angularjs api callback ngresource

我正在用ngresource写一个工厂,虽然它在成功回调中打印了值,但它并没有将值返回给控制器。我在控制台中收到Undefined。

sum({@check},{Employee})=0

2 个答案:

答案 0 :(得分:0)

我认为您应该尝试在return方法中声明getJsonId语句

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

并在controller中调用此方法,如

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

答案 1 :(得分:0)

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.