Search code examples
angularjsputngresource

How to send a put-request with body in Angular with ngResource


I can send a put-request with a header with ngResource. My FactoryService looks like this:

angular
.module("playersServicesModule", ["ngResource", "config"])
.factory("playersService", ["$resource", "API_ROOT",

  function ($resource, API_ROOT) {
    "use strict";

    var url = API_ROOT + "/api/footballplayers";

    return {

      updateFootballPlayer: function (id, column, newValue) {

        return $resource(url + '/:Id', { Id: id },
                {
                  "update": {
                    method: 'PUT', headers: {
                      "Column": column,
                      "NewValue": newValue
                    }
                  }
                });
      }

    };

How can i add data to the body of the put-request?


Solution

  • UPDATE

    A suggested update to your factory would be the following:

    angular
    .module("playersServicesModule", ["ngResource", "config"])
    .factory("playersService", ["$resource", "API_ROOT",
    
        function ($resource, API_ROOT) {
            "use strict";
    
            var url = API_ROOT + "/api/footballplayers";
    
            var myResource = $resource(url + '/:Id',
                    { Id: '@id },
                    {
                        "update": {
                            method: 'PUT'
                        }
                    });
    
            return {
    
                updateFootballPlayer: function (id, column, newValue) {
    
                    return myResource.update(
                        {Id: id},
                        {
                            column: column,
                            newValue: newValue
                        },
                        function (successResponse) {
                            // Do something on success
                        },
                        function (failResponse) {
                            // Do something on fail
                        }
                    );
                }
    
            };
        });
    

    ORIGINAL

    You add data to the body when you perform the actual request e.g.

    $resource(url + '/:Id', { Id: id },
        {
            "update": {
                method: 'PUT',
                headers: {
                    "Column": column,
                    "NewValue": newValue
                }
             }
        }
    ).update(
        {},
        <BODY_OBJECT>,
        function (successResponse) {},
        function (failResponse) {}
    );
    

    Your object to pass as body data will replace the <BODY_OBJECT>.