简体   繁体   中英

Removing values from array and adding them to POST method request

I have a cart in my AngularJS app and I need to identify the items through their id through a POST method.

They are stored in an array called patent_ids and are appended to the request like so:

 var cartArr = [];
 var cartItems = ngCart.getItems()

 cartItems.forEach(function(currentValue, index, array){
     cartArr.push(currentValue._id)
  })

  var obj = {
      patent_id: cartArr
  };

  fetchBasketPatents(obj);

function fetchBasketPatents(obj) {
    //load of code to call service and pass the ids
}

var REST_SERVICE_URI = 'http://localhost:8080/p3sweb/rest-basket/';

factory.fetchBasketPatents = function(ids) {

    var deferred = $q.defer();

    $http.post(REST_SERVICE_URI, ids) //REQUEST TO BACK END WITH IDS
    .then(
        function(response){
            deferred.resolve(response.data)
        },
        function(errResponse){
            deferred.reject(errResponse)
        }
    )

    return deferred.promise;

}

It works but it would be easier if rather than sending the ids in a named array, they could be sent as an anonymous array, or even better each item extracted an inserted into an anonymous object.

Question

How do I send the ids in the POST request in either an anonymous array or object? Apologies if I am missing something obvious.

How do I send the ids in the POST request in either an anonymous array or object?

From Document:

   $http.post('/someUrl', data, config).then(successCallback, errorCallback);

Where data{string|Object}

So the answer is: you cannot define anonymous array but object only (like you did)

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