I'm not a veteran of JavaScript and I have a little problem :
In an AngularJS controller, I get 2 arrays from a WebService of the form [{"id":"1", "name":"aname1"}, {"id":"2", "name":"aname2"}]
. They have both the same structure (this shouldn't be important).
With concat()
or push()
I'm unable to merge these arrays together, and I don't understand why.
I tried
var arrayS = Service.list(); // Get data from WebService
var arrayAE = ActeurExterne.list(); // Idem
var arrayRes = arrayS.concat(arrayAE);
$scope.acteurs = arrayRes;
In my AngularJS app, the array acteurs
is empty (if I displays it outside a ng-repeat
loop, it displays []
while arrayS and arrayAE display their contents)
And the same logic with :
array1.push.apply(array1, array2);
I tried to push elements of array2 one by one in a for loop, same result.
Nothing worked. Why?
Use this
Did you assign the result to another variable? For example:
The
.concat()
method returns a new Array with the concatenated elements.MDN Documentation on
Array.prototype.concat
You're actually merging the arrays correctly and both methods would work (provided like others said that you use the return value of
concat
), but the result is empty because you're doing it when the answers from the ajax requests didn't arrive yet and the arrays are still empty.When making ajax requests you must manipulate the result inside the success callback function, not at the same level of the ajax request code; for example
will NOT work, because it's attempting to use the content of
myvec
right after the request has been submitted but before the reply arrived. Correct code is instead:If you need to concatenate the results of two async queries you must either chain them (make the second query only once the first returned) or you must wait for the second one to complete:
or
This crazy guess is simply coming from the frequency that this kind of error has in beginner code.
concat()
will return a new array, not concat to thethis
. So: