Search code examples
angularjsapipostrequestangular-resource

Angular $resource: object id lost using POST with custom methods


I want to use a custom method in my Foo Factory with a POST call. When I call it as a GET request, it works, but it's deny by my api because it doesn't allow GET for that method.

Request: GET /api/foo/272ee694-b517-4012-b740-98f76973091d/custom_method/ 405

When I change the method to POST (in the angular factory), the object id disapears:

Request: OPTIONS /api/foo/custom_method/ 174

Request: POST /api/foo/custom_method/ 405

Note that this time an OPTION request is made before without the id.

My factory looks like:

appService.factory('foo', ['$resource', 'appConfig',
  function($resource, appConfig){

    var api_path = appConfig.api_path;

    return $resource(api_path + 'foos/:fooId/', {fooId:'@id'},{
      query: {
        method: 'GET',
        isArray: false
      },
      customMethod: {
        method: 'POST',
        url: api_path + 'foos/:fooId/custom_method/'
      }
    });
  }]);

And my controler:

$scope.foo = foo.get({fooId: $routeParams.fooId});

$scope.customMethod = function() {
    foo.customMethod({fooId:$scope.foo.id});
}

Anyone could help me? Thank you in advance


Solution

  • So, I found the solution. In the controller, just call custom_method from the object with a $. Like this:

    $scope.foo.$custom_method();
    

    You can also omit to pass the id because $resource get it from the object by default.