angular.extend在Angularjs应用程序中无法合并2个数组

时间:2016-12-05 23:07:22

标签: javascript angularjs promise angular-promise

我想合并两个数组但结果总是为null。我不知道这里的问题是我的代码:

$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);

消息是一种服务。

2 个答案:

答案 0 :(得分:0)

angular.extend用于合并对象,而不是数组。你可能想在这里使用Array.concat

$scope.messages = $scope.messages
                        .concat($scope.messagesRecieved)
                        .concat($scope.messagesSent);

答案 1 :(得分:0)

我猜你只使用$scope.messagesRecieved$scope.messagesSent作为中间词来推导$scope.messages,而不是用于推动视图。

如果是这样,它们就会消失,messagesRecieved / messagesSent可以从Promise.all()开始的承诺链中传递,以汇总您的两个Message.getMessengerMessages()承诺。

此外,要连接数组,请使用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);
});