推功能似乎覆盖了Angular

时间:2019-03-19 19:50:14

标签: arrays json angular

我正在尝试使用以下代码将一些对话消息推送到数组中:

myConversations: IConversation[] = [];
myConversationMessage: IConversationMessages = {
conversationId: 0,
messageId: 0,
messageText: ''
};
myConversationMessages: IConversationMessages[] = [];

this.conversationService.getConversations().subscribe(conversations => {
  this.myConversations = conversations;

  for (let i of this.myConversations) {
    this.myConversationMessage.conversationId = i.conversationId;       
    for (let j of i.messages) {
      this.myConversationMessage.messageId = j.messageId;
      this.myConversationMessage.messageText = j.messageText; 
      this.myConversationMessages.push(this.myConversationMessage);
    }
  }

  console.log(this.myConversationMessages);
});

我正在从JSON对象检索其中的对话和消息。 而不是将每个消息推送到 myConversationMessages 数组,而是在控制台中输出以下内容:

0 
conversationId: 2
messageId:2
messageText: "testing"

1
conversationId: 2
messageId:2
messageText: "testing"

2
conversationId: 2
messageId:2
messageText: "testing"

3
conversationId: 2
messageId:2
messageText: "testing"

因此,最终的“对话”对象将覆盖每个数组元素。

有人可以告诉我为什么我的代码这样做吗?提前谢谢

P.S。如果可以解决我的问题,我可以上传更多代码。

2 个答案:

答案 0 :(得分:0)

发生这种情况是因为您将引用对象添加到了数组中。在您的示例中,您没有向数组添加3个对象,而是对一个对象添加了3次引用。其中之一的属性更改会导致所有其他属性的更改。

应该可行:

for (let i of this.myConversations) {
    this.myConversationMessage.conversationId = i.conversationId;       
    for (let j of i.messages) {
      let item = new IConversationMessages();
      item.messageId = j.messageId;
      item.messageText = j.messageText; 
      this.myConversationMessages.push(item);
    }
  }

答案 1 :(得分:0)

这是因为JavaScript对象是通过引用传递的:

myConversationMessages: IConversationMessages[] = [];

this.conversationService.getConversations().subscribe(conversations => {
  this.myConversations = conversations;

  for (let i of this.myConversations) {
    this.myConversationMessage.conversationId = i.conversationId;       
    for (let j of i.messages) {
      this.myConversationMessage.messageId = j.messageId;
      this.myConversationMessage.messageText = j.messageText; 
      this.myConversationMessages.push(this.myConversationMessage); // <-= Here you are pushing a reference to the same object in every loop. In every loop you are updating the single object, and the reference in each array spot points to the same object
    }
  }

  console.log(this.myConversationMessages);
});

尝试一下:

  for (let i of this.myConversations) {
    for (let j of i.messages) {
      this.myConversationMessages.push({
          conversationId: i.conversationId,
          messageId: j.messageId,
          messageText: j.messageText
      });
    }
  }

这将为每次迭代创建一个新对象