1

I wanna merge two arrays but the result always is null. I dont know whats the problem here is my code :

$scope.messages=[];
$scope.messagesRecieved=[];
$scope.messagesSent=[];
Message.getMessengerMessages(localStorage.getItem("token"),localStorage.getItem("contact")).then(function(messages){


 $scope.messagesRecieved=messages;

})
console.log('le contact est '+localStorage.getItem("contact") +'Lutilisateur est  '+localStorage.getItem("token"))
Message.getMessengerMessages(localStorage.getItem("contact"),localStorage.getItem("token")).then(function(messages){


 $scope.messagesSent=messages;
 for (var i=0; i<messages.length; i++) {
  if(messages[i].read=='no'){
    Message.modifyRead(messages[i]._id);
  }
 }
})
angular.extend( $scope.messages, $scope.messagesRecieved, $scope.messagesSent);

Message is a service.

Alexandre Neukirchen
  • 2,713
  • 7
  • 26
  • 36
juliana Morales
  • 177
  • 3
  • 3
  • 10
  • The `Message` API is asynchronous. Push the data to `$scope.messages` array from *inside* each `.then` block. – georgeawg Dec 06 '16 at 02:49
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – georgeawg Dec 06 '16 at 02:53

2 Answers2

0

angular.extend is used to merge objects, not arrays. You probably want to use Array.concat here.

$scope.messages = $scope.messages
                        .concat($scope.messagesRecieved)
                        .concat($scope.messagesSent);
musically_ut
  • 34,028
  • 8
  • 94
  • 106
0

I'm guessing you only use $scope.messagesRecieved and $scope.messagesSent as intermediates, for deriving $scope.messages, not for driving the view.

If so, they can disappear and messagesRecieved/messagesSent can be delivered down a promise chain starting with Promise.all() to aggregate your two Message.getMessengerMessages() promises.

Also, to concatenate arrays, use newArray = array1.concat(array2).

// $scope.messagesRecieved = []; // not necessary unless there's a corresponding view element
// $scope.messagesSent = []; // not necessary unless there's a corresponding view element
$scope.messagesSent = []; // you only need to do this if you want to nullify a view element while the two async gets are underway.

var receivedPromise = Message.getMessengerMessages(localStorage.getItem('token'), localStorage.getItem('contact'));

var sentPromise = Message.getMessengerMessages(localStorage.getItem('contact'), localStorage.getItem('token')).then(function(messages) {
    for(var i=0; i<messages.length; i++) {
        if(messages[i].read == 'no') {
            Message.modifyRead(messages[i]._id); // if Message.modifyRead() is async, this code block is a bit different
        }
    }
});

Promise.all(receivedPromise, sentPromise).then(function(messagesRecieved, messagesSent) {
    $scope.messages = messagesRecieved.concat(messagesSent);
});
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44