如何使用ngResource在Angular中发送带有body的put-request

时间:2016-02-18 22:44:19

标签: angularjs put ngresource

我可以发送带有ngResource标头的put-request。我的FactoryService看起来像这样:

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
                    }
                  }
                });
      }

    };

如何将数据添加到put-request的主体?

1 个答案:

答案 0 :(得分:3)

<强>更新

您工厂的建议更新如下:

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

执行实际请求时,您可以向正文添加数据,例如

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

作为正文数据传递的对象将替换<BODY_OBJECT>