Javascript 默认 $resource POST 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11239892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:05:11  来源:igfitidea点击:

Default $resource POST data

javascriptangularjs

提问by Nimaen

That might be strange but I need to specify some default POST data for my $resource using the factory method of the module.

这可能很奇怪,但我需要使用模块的工厂方法为我的 $resource 指定一些默认的 POST 数据。

Does anyone have an idea of how to do that in AngularJS ?

有没有人知道如何在 AngularJS 中做到这一点?

EDIT :

编辑 :

Well, i want to do something like this :

好吧,我想做这样的事情:

/**
 * Module declaration.
 * @type {Object}
 */
var services = angular.module("services", ["ngResource"]);

/**
 * Product handler service
 */
services.factory("Product", function($resource) {
    return $resource("http://someUrl", {}, {
        get   : {method: "GET", params: {productId: "-1"}},
        update: {method : "POST", params:{}, data: {someDataKey: someDataValue}}
    });
});

Where data is the default data for my future POST requests.

其中 data 是我未来 POST 请求的默认数据。

回答by Bogdan Rybak

This is not really the angular way to do such a thing as you lose data consistency if you do it and it doesn't reflect in your model.

这并不是真正的角度方式来做这样的事情,因为如果你这样做,你会失去数据一致性,并且它没有反映在你的模型中。

Why?

为什么?

The resource factory creates the object and uses object instance data as POST. I have looked at the documentation and angular-resource.js and there doesn't seem to be a way to specify any default custom properties for the object being created by resource without modifying angular-resource.js.

资源工厂创建对象并使用对象实例数据作为 POST。我查看了文档和 angular-resource.js,似乎没有办法在不修改 angular-resource.js 的情况下为资源创建的对象指定任何默认自定义属性。

What you can do is:

你可以做的是:

services.factory("Product", function($resource) {
    return $resource("http://someUrl", {}, {
        get   : {method: "GET", params: {productId: "-1"}},
        update: {method : "POST"}
    });
});

and in your controller:

并在您的控制器中:

$scope.product = {}; // your product data initialization stuff
$scope.product.someDataKey = 'someDataValue'; // add your default data

var product = new Product($scope.product);
product.$update();

回答by nesty

I think most have missed a tiny gem in the documentation here.

我认为大多数人都错过了此处文档中的一个小宝石。

non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

This suggests you can do the following.

这表明您可以执行以下操作。

var User = $resource('/user');
postData = { name : 'Sunil', 'surname' : 'Shantha' };

var user = User.save({notify:'true'}, postData, function() {
  // success!
});

The second parameter when doing a save action (post) is post data.

执行保存操作(发布)时的第二个参数是发布数据。

回答by Foo L

I think it will depend on how you call the update function. If you read the angular main page's tutorial, under "Wire up a Backend", the mongolab.js provides a 'Project' factory. Copied verbatim:

我认为这取决于您如何调用更新功能。如果您阅读了 angular 主页的教程,在“连接后端”下,mongolab.js 提供了一个“项目”工厂。逐字复制:

angular.module('mongolab', ['ngResource']).
factory('Project', function($resource) {
  var Project = $resource('https://api.mongolab.com/api/1/databases' +
      '/angularjs/collections/projects/:id',
      { apiKey: '4f847ad3e4b08a2eed5f3b54' }, {
        update: { method: 'PUT' }
      }
  );

  Project.prototype.update = function(cb) {
    return Project.update({id: this._id.$oid},
        angular.extend({}, this, {_id:undefined}), cb);
  };

  Project.prototype.destroy = function(cb) {
    return Project.remove({id: this._id.$oid}, cb);
  };

  return Project;
});

The usage is that you first get an instance of the Project:

用法是先得到一个Project的实例:

project = Project.get({id:1});

Then do an update after some changes:

然后在一些更改后进行更新:

project.update(someFunction);

In your case, you can change the update to always add the data you need:

在您的情况下,您可以更改更新以始终添加您需要的数据:

Product.prototype.update = function(cb) {
  return Product.update({},
      angular.extend({}, this, {someDataKey: someDataValue}), cb);
};

Otherwise, you can most likely put the key/value pair in the params:

否则,您很可能将键/值对放在参数中:

    update: {method : "POST", params:{someDataKey: someDataValue}}

It will be POSTed with the key/value pair in the URL, but most app servers nowadays will throw the pair into the params object anyway.

它将与 URL 中的键/值对一起发布,但现在大多数应用服务器无论如何都会将键/值对扔到 params 对象中。

回答by kfis

Might this solve your problem?

这能解决你的问题吗?

services.factory("Product", function($resource) {
  return $resource("http://someUrl", {}, {
    get   : {method: "GET", params: {productId: "-1"}},
    update: {method : "POST", params:{}, data: {someDataKey: someDataValue}}
  });
});
services.factory("DefaultProduct", function(Product) {
  return function(){
     return new Product({
        data:"default";
     });
  };
});
services.controller("ProductCTRL",function($scope,DefaultProduct){
  $scope.product = new DefaultProduct();
});

回答by MatthiasLaug

You can just mergeyour params with the default. Everything notavailable in paramswill be provided by the default object. Everything available will be overwritten by myParams

您可以您的参数与默认值合并。中不可用的所有内容params将由默认对象提供。可用的所有内容都将被覆盖myParams

services.factory("Product", function($resource) {
    return $resource("http://someUrl", {}, {
        get   : {method: "GET", params: {productId: "-1"}},
        update: {method : "POST", params:angular.extend(myDefault, myParams);}
    });
});

where myParamswould be your list of variables and myDefaultyour default values as a json object.

myParams您的变量列表和myDefault作为 json 对象的默认值在哪里。

回答by R?mulo Bourget Novas

You can set default fields on your request by using transformRequestoption for your $resource's actions that use the POSTmethod.

您可以通过为使用POST方法的$resource操作使用transformRequest选项来设置请求的默认字段。

For example something like this

例如这样的事情

function prependTransform(defaults, transform) {

 // We can't guarantee that the default transformation is an array
 defaults = angular.isArray(defaults) ? defaults : [defaults];

 // Append the new transformation to the defaults
 return [transform].concat(defaults);
}

ctrl.factory('MyResource', ['$resource', '$http',
function($resource, $http) {
    return $resource('/path/to/myresource/:id', {id : '@id'},
           { 
               create : {
                   method : 'POST',
                   transformRequest : prependTransform($http.defaults.transformRequest,
                      function(data, headers) {
                           return addDefaultField(data);
                      }
                  ),
               },
           });
    }
]);

回答by Andrew Joslin

Wrapper function will work.

包装功能将起作用。

function myPost(data) {
  return $http.post('http://google.com', angular.extend({default: 'value'}, data))
}

myPost().success(function(response) { ... });