Can't figure out why ng-resource won't return array

 ̄綄美尐妖づ 提交于 2019-12-25 05:25:07

问题


I am using AngularJS and NGResource and I can't figure out why when I use query, I keep getting an empty array back.

In my controller, I am doing

Task = $resource('/tasks'); 
var tasks = Task.query(function () {});
console.log(tasks);
$scope.tasks = tasks;

In the view

{{tasks}}

In the view it displays correctly

[{"created_at":"08/08/2013","created_by_id":2,"description":"description","id":1,"name":"test task 1","parent_task_id":null,"task_type_id":1,"updated_at":"08/08/2013"},
{"created_at":"08/08/2013","created_by_id":2,"description":"description","id":2,"name":"test task 2","task_type_id":1,"updated_at":"08/08/2013"}]

but in the console it gets logged as an empty array:

[]

Also, i'm using batarang extension for chrome and the scope that it shows tasks as having is:

tests: 
  [  ]

I need to perform some data operations on the returned value before I put it into the $scope model. Is this typical behavior and theres something i'm missing? Or am I doing something wrong? Any ideas would be appreciative. I've been stuck on this for too long.


回答1:


You're logging the empty array before it's been populated by the asynchronous AJAX result.

Part of Angular's magic is that it'll automatically update the tasks array with the new data as it comes down the wire, and also auto update the view.

As proof, try this:

var Task = $resource('/tasks');

$scope.tasks = Task.query(function () {});;

$scope.$watch('tasks', function (value) {
    console.log(value);
});

Here's a quote from the docs:

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods.



来源:https://stackoverflow.com/questions/18222928/cant-figure-out-why-ng-resource-wont-return-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!