Search code examples
javascriptangularjspromiseangular-resource

$promise stays promised on 'then' function


I'm using angular's $resource to perform a GET operation. This is how I do it:

var query = {customerid: $stateParams.customerid}    
$resource('api/reports/running_count').get(query).$promise.then(function(value) {
    $scope.runningInstance = value;
});

I also tried it like that:

$resource('api/reports/running_count').get(query, function(value) {
    $scope.runningInstance = value;
});

The request returns a number. I checked the response with chrome's developer-tools. The request is indeed sent as follows:

<base-url>/api/reports/running_count?customerid=<id>

The response returns a number, again as expected.

But when I put a breakpoint in the callback function, the value is again a promise and not a number. Not sure what I'm doing wrong.


Solution

  • The $resource service doesn't work when the response is a primative. It uses angular.copy to copy the data to the $resource object and angular.copy doesn't copy a primative to an object. It can only make deep copies of properties of other objects.

    From the Docs:1

    angular.copy

    Creates a deep copy of source, which should be an object or an array.

    • If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

    • If source is not an object or array (inc. null and undefined), source is returned.

    In your case the source was not an object and you were getting just the $promise property which the $resource service attaches to the resource object.