Search code examples
javascriptangularjsrestangular-resourceangularjs-resource

Using $resource with rest service


I'm trying to get familiar with $resource in order to use RESTful Web Services.

So, for the attempt, I declared a factory like this :

'use strict';

angular.module('BalrogApp').factory('Req', ['$resource', function($resource) {
  return $resource('http://localhost:8000/api/catalog/requests/:id', {id: '@id'}, {
    'update': { method: 'PUT'},
    'query': { method: 'GET'}
  });
}]);

In my Controller I have this :

angular.module('BalrogApp').controller('requestsController', function(Req, $route, $rootScope, $scope, $location, $routeParams) {
  this.$route = $route;
  var controllerScope = this;

  this.r = Req.get({ id:4 });

  console.log(this.r);

This works fine, in my console, I can see my object with the data retrieved from the services for the item with id 4.

However I'm not sure I'm properly retrieving the data since the object i'm storing in r contains an id like it should in the object details (clicking on "Object" in the browser console displays the object details including its id) but the object itself (r) displayed on the console contains only 2 fields and is presented as follows : Object { $promise: Object, $resolved: false }.

So, in the end, console.log(this.r); works but console.log(this.r.id); doesn't even if r is supposed to contain an id just like in the object details from the browser inspector.

Also, how can I configure this service in order to be able to use get() with the id parameter just like I'm doing which results in calling http://localhost:8000/api/catalog/requests/:id but also without the id parameter which results in calling http://localhost:8000/api/catalog/requests


Solution

  • As the call to the REST API is asynchronous you shout wait for the returned promise to resolve when using the Req.get({ id:4 });

    Use:

    Req.get({ id:4 }).$promise.then(function(result){
      console.log(JSON.stringify(result));
    });
    

    instead.

    For the second part of your question: Using data without an id property should be fine. This data, however, will be transfered in the request body and not as a request parameter.