angularjsasp.net-web-api2ngresource

Resolved ngResource promise contains no data


I have a Web Api controller which contains the following method:

[Route("CountThings/{id}")]
[HttpGet]
public async Task<IHttpActionResult> CountThings(int id)
{
    //var numberOfThings = await _thingsRepository.CountThingsAsync(id);
    return Ok(123456);
}

As you can see, I'm always returning Ok with 123456 as data. This is for test purpose only.

In my Angular resource file I have this:

getCountThings: {
    method: 'GET',
    url: controllerPath + 'CountThings/:id',
    params: { id: '@id' }
}

And in my angular controller I have this:

thingsResource.getCountThings({ id: scope.id })
.$promise
.then(function (data) {
    console.log(data);
    scope.numberOfThings = data;
 });

When I debug my application I can see that the API controller is called and returns correctly. In my angular controller I can see that the promise have been resolved when I log the data. But, I can't find a way to get to the data that should be returned (123456). If I log data.$resolved, this returns true.

How do I access the data that I want to use in my controller?


Solution

  • You can't get primitives using angular $resource. Try returning json object from server (like { data: 123456 }):

    thingsResource.getCountThings({ id: scope.id })
    .$promise
        .then(function (result) {
            scope.numberOfThings = result.data;
        });
    

    See this issue and explanation why resource has to be an object.

    Alternative is to use $http service:

    $http.get(controllerPath + 'CountThings/' + scope.id).then(function (result) {
        scope.numberOfThings = result.data;
    });
    

    In this case you don't need to modify anything on server.