Default $resource POST data

前端 未结 7 1248
天命终不由人
天命终不由人 2021-02-07 11:51

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

Does anyone have an idea of how to do that in

7条回答
  •  我寻月下人不归
    2021-02-07 12:22

    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.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.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.

提交回复
热议问题