$resource 没有从 json 获取数组

$resource doesn't get array from json

我想从服务器 (java) 获取数组对象。下面是angular方法:

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分配给返回的服务器数据。

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

Angular $resource 在有 isArray:true 的动作存在时有一点不一致。

如果您调用资源 class 而不是实例,则有不同的工作方式,例如:

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