Ken
Ken

Reputation: 3141

Posting multiple arrays with $http service in AngularJS

I am using and have two arrays that I would like to post to a server to be processed and sent in a confirmation email. Any thoughts on the how to properly submit these arrays?

Here are the two arrays:

var array1 = vm.contacts;
var array2 = vm.projects;

$http service:

data = array1; // Is it possible to add array2 here too?

$http.post('http://localhost:9000/api/emails', data)
  .then(function(response) {
      console.log(response);

    }, function(response) {
      console.log('error', response);
    }

Upvotes: 1

Views: 1294

Answers (1)

You could send an object that contains those arrays. Something like this:

var vm = {};
vm.contacts = []; // Array of contacts.
vm.projects = []; // Array of projects.
var data = vm; // Object with arrays.

In your $http service:

$http.post('http://localhost:9000/api/emails', data)
    .then(function (response) {
    console.log(response.data); // Use response.data to show your response.
}, function (response) {
    console.log('error', response);
}

Updated:

By this way you might to send arrays of arrays. Something like this:

var vm = {};
vm.contacts = [];
vm.projects = [];

var arrays = [];
var array1 = vm.contacts;
var array2 = vm.projects;

arrays.push(array1, array2);
console.log(arrays);
var data = arrays;

Then:

In your $http service:

$http.post('http://localhost:9000/api/emails', data)
    .then(function (response) {
    console.log(response.data); // Use response.data to show your response.
}, function (response) {
    console.log('error', response);
}

Upvotes: 3

Related Questions