admin管理员组文章数量:1415697
I am new to AngularJS, so please be gentle.
I want to retrieve data from my backend using the $resource property of AngularJS, however it seems that the property is getting loaded before the actual call is pleted.
Currently I have the following code:
Controller:
MyApp.controller('IndexCtrl', function IndexCtrl($scope, socket, carsRes) {
console.log(carsRes.cars.get());
$scope.cars = carsRes.cars.get();
});
Factory
.factory('carsRes', function($resource) {
var result = {};
result.cars = $resource('/cars/:id', {}, {
'get': {method: 'GET'},
'save': {method: 'POST'},
'query': {method: 'GET', isArray: true},
'remove': {method: 'DELETE'},
'delete': {method: 'DELETE'}
});
return result;
});
But at the point where I want to store carsRes.cars.get() in $scope.cars the call isn't pleted yet, and a console.log tells me that the $resolved is still false.
How can I wait for the call to be resolved? I've read something about $q but it isn't really clear to me.
I am new to AngularJS, so please be gentle.
I want to retrieve data from my backend using the $resource property of AngularJS, however it seems that the property is getting loaded before the actual call is pleted.
Currently I have the following code:
Controller:
MyApp.controller('IndexCtrl', function IndexCtrl($scope, socket, carsRes) {
console.log(carsRes.cars.get());
$scope.cars = carsRes.cars.get();
});
Factory
.factory('carsRes', function($resource) {
var result = {};
result.cars = $resource('/cars/:id', {}, {
'get': {method: 'GET'},
'save': {method: 'POST'},
'query': {method: 'GET', isArray: true},
'remove': {method: 'DELETE'},
'delete': {method: 'DELETE'}
});
return result;
});
But at the point where I want to store carsRes.cars.get() in $scope.cars the call isn't pleted yet, and a console.log tells me that the $resolved is still false.
How can I wait for the call to be resolved? I've read something about $q but it isn't really clear to me.
Share Improve this question asked Apr 13, 2013 at 14:07 DirkZzDirkZz 2,2292 gold badges16 silver badges11 bronze badges 1-
After poking around some more I found something that works:
carsRes.cars.get(function(data){ $scope.cars = data.doc; });
Is this a proper solution? – DirkZz Commented Apr 13, 2013 at 14:32
1 Answer
Reset to default 6This is happening because resource.get()
is asynchronous. It returns an empty reference immediately, and is then populated with the actual data once the ajax call is plete.
The best way to handle the result is with a callback function:
carsRes.cars.get(function(response){
// We now have a pleted ajax call, with the response
$scope.cars = response;
});
See more examples in the $resource
documentation.
本文标签: javascriptAngularJS Resource not ResolvedStack Overflow
版权声明:本文标题:javascript - AngularJS Resource not Resolved - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745238739a2649193.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论