2

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.

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? Commented Apr 13, 2013 at 14:32

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually - unlike $http, the ngResource object methods doesn't return a promise: 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.
@joakimbl Thanks for the correction! I was thinking $http. Updated the answer.
I was looking for a promise on ngResource as well.. Thanks for pointing out! So you also can't resolve a route using ngResource?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.