AngularJS Resource not Resolved

angularjs, javascript, promise, resources

Solution

This 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 complete.

The best way to handle the result is with a callback function:

carsRes.cars.get(function(response){ 
    // We now have a completed ajax call, with the response
    $scope.cars = response;
});

See more examples in the `$resource` documentation.

Problem

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 completed. 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 completed 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.

Original source