简体   繁体   中英

Posting to a REST interface

need to define the name as ID in the URL and need to post an object containing data.

$scope.dvModel.naam is the name that acts as the ID. filteredObject is the object containing the data, obviously.

This is how I call the service, seems ok according to some examples.

saveDVservice.query($scope.dvModel.naam, filteredObject);

This is the actual service.

.factory('saveDVservice', ['$resource', 'CONSTANTS', function($resource, CONSTANTS) {
    'use strict';
    return $resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
}]);

This is what I see in my network tab at Query String Parameters: 0:A 1:D 10:n 11:h 12:i 13:l 14:f 15:e 2:A 3:C 4: 5:P 6:a 7:n 8:n 9:e

Which is the name, but looks like an array.

Request Payload contains the actual object in correct order. Can one give me some guidance on how to handle this?

As I understand, you want to put $scope.dvModel.naam into URL and you want filteredObject to be a request payload. Then you need an object that contains everything that's in filteredObject and additionaly under the key name a value equal to $scope.dvModel.naam .

Also, the definition of your resource probably should change - in second argument $resource requires you to tell it the way of extracting URL data from given object:

$resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {name: '@name'}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});

Unfortunately, $resource isn't the best $http wrapper to use when your payload data is separated from URL data. Maybe it would be better to wrap the filteredObject data in payload in some other object? Then your $resource object would be much nicer, like {name: ..., data: {"0": "A", "1": "D", ...}}

Since default action for query is {method: 'GET', isArray: true} , I'd leave that be and use another default, save instead. That should work out-of-the-box.

app.factory('DVService', function ($resource) {
  return $resource(CONSTANTS.REST_BASE_URL + '/dv', {name: '@name'}, {}); 
}); 

.

app.controller('MainCtrl', function ($scope, DVService) {
  var postData = {
    name: 'name',
    fooProp: 'foo',
    barProp: 'bar'
  };

  // save/post        
  DVservice.save({dv: postData}).$promise.then(function (response) {
    console.log(response);
  });

  //query/get
  DVService.query({name: 'name'}).$promise.then(function (response) {
    console.log(response);
  });
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM