我想从服务器(java)获取数组对象。下面是角度方法:
service.getAthors = function(){
var deferred = $q.defer();
var authors = authorResource.query(function() {
console.log(authors);
}).$promise.then( function(){
deferred.resolve( "Adding book have gone correctly." );
}, function(){
deferred.reject("Error during adding new book.");
});
}
在控制台firebug中我看到:[{"author_id":7,"author":"Dan Brown"}]
但是authors数组为空。你能告诉我为什么吗?
答案 0 :(得分:1)
您需要将authors
分配给返回的服务器数据。
authorResource.query(function() {
console.log(authors);
}).$promise.then( function(data){
authors = data;
deferred.resolve( "Adding book have gone correctly." );
}, function(){
deferred.reject("Error during adding new book.");
});
答案 1 :(得分:0)
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
authorResource.query({isArray:true},function() {
console.log(authors);
}).$promise.then( function(data){
authors = data;
deferred.resolve( "Adding book have gone correctly." );
}, function(){
deferred.reject("Error during adding new book.");
});
您正在使用查询方法使用isArray:true
参见参考https://docs.angularjs.org/api/ngResource/service/ $ resource
答案 2 :(得分:0)
当存在isArray:true的操作时,Angular $资源有一点不一致。
如果您调用资源类而不是实例,则以不同方式工作,例如:
myModule.controller('controller',function(MyResource){
//In this MyResource is the class
var myElement = MyResource.get({id:1}); //myElement is an instance
var array = MyResource.query(); //When the query response the array gonna be filled
var arrayFromMyElement = myElement.query() // Return a promise not a array and the data of the promise gonna get the array
arrayFromMyElement.then(function(data){
//Data is the array
})
});
这可以在$ resource源代码中观察到:
https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L627-L638