【问题标题】:AngularJS $resource - POST with id paramAngularJS $resource - 带有 id 参数的 POST
【发布时间】:2017-03-31 17:12:17
【问题描述】:

我有一个 angularJS $resource:

$resource("http://localhost:3000/:id",{
   id: '@id'
},
{
   get: {
      method:'GET',
      isArray: false
   },
   foo: {
      method:'POST',
      url: 'http://localhost:3000/:id/foo',
      isArray: false
   }
});

现在如果我打电话:

User.foo({id:'123', anotherParam: 'bar'});

这会导致 URL 'http://localhost:3000/foo' 被调用并将 id 和 anotherParam 参数作为 POST 字段传递。

我实际上希望它调用 'http://localhost:3000/123/foo' 并且只将 anotherParam 参数作为 POST 字段传递。

如何让 id 参数正常运行?

【问题讨论】:

    标签: angularjs angular-resource


    【解决方案1】:

    https://docs.angularjs.org/api/ngResource/service/$resource

    非 GET “类”操作:Resource.action([parameters], postData, [success], [error])

    你需要做的:

    User.foo({id:'123', anotherParam: 'bar'}, <post data object>);
    

    当您使用单个参数调用函数时。它假定可选参数不存在并将其作为 postData 发送。

    【讨论】:

      【解决方案2】:

      接受的解决方案对我不起作用 (AngularJS v1.4.8)。 必须手动设置内容类型并转换为表单数据。

      示例:

      var DirectoryApi = $resource('api/directories', null, {
          move: {
              url: 'api/directories/:name/_move',
              params: {"name" : "@name"},
              headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
              transformRequest: function (param) {
                  return $.param(param);
              },
              method: 'POST'
          },
      });
      

      及用法:

      function moveDirectory(name, parent, after) {
          return DirectoryApi.move({name: name}, {parent: parent, after: after});
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-29
        • 2015-12-24
        • 1970-01-01
        • 1970-01-01
        • 2014-04-22
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        相关资源
        最近更新 更多