gpt4 book ai didi

json - 如何在 Angular 中基于外部 NgFor 建立内部 NgFor

转载 作者:太空狗 更新时间:2023-10-29 17:49:02 27 4
gpt4 key购买 nike

我试图在我的 Angular 应用程序中显示对话列表,然后在每个对话标题下显示这些不同对话中包含的消息。

这是我最新的代码-

HTML:

<div
class="card"
style="width: 18rem;"
*ngFor="let conversation of myConversations"
>
<div class="card-body">
<h5 class="card-title">{{ conversation.conversationTitle }}</h5>
<h6 class="card-subtitle mb-2 text-muted">
Conversation ID: {{ conversation.conversationId }}
</h6>
<p *ngFor="let message of myConversationMessages" class="card-text">
{{ message.messageText }}
</p>
</div>

TS:

myConversations: IConversation[] = [];
myConversationMessage: IConversationMessages = {
conversationId: 0,
messageId: 0,
messageText: ''
};
myConversationMessages: IConversationMessages[] = [];
constructor(private conversationService: ConversationService) {}

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

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

这是我目前能够显示的内容:

enter image description here

每个对话都有自己的卡片,但所有对话都会重复消息,无论它们连接到哪个对话。

我认为我需要对内部 ngFor 进行一些更改,但我不确定要进行哪些更改。关于需要进行哪些更改的任何想法?谢谢!

此外,这是相关的 JSON:

[
{
"conversationId": 1,
"conversationTitle": "My first convo",
"messages": [
{
"messageId": 1,
"messageText": "Hi"
},
{
"messageId": 2,
"messageText": "Hello"
}
]
},
{
"conversationId": 2,
"conversationTitle": "My second convo",
"messages": [
{
"messageId": 1,
"messageText": "test"
},
{
"messageId": 2,
"messageText": "testing"
}
]
}
]

最佳答案

根据您提供的 JSON,您应该能够在 *ngfor 中使用 *ngfor 来读取消息。我已经去掉了一些元素,但下面应该会给你你需要的结果。基于问题中的 JSON。

解决方案

<div class="card" style="width: 18rem;" *ngFor="let conversation of myConversations">
<div class="card-body">
<h5 class="card-title">
{{ conversation.conversationTitle }}
</h5>

<h6 class="card-subtitle mb-2 text-muted"> Conversation ID:
{{ conversation.conversationId }}
</h6>

<div *ngFor="let message of conversation.messages" class="card-text">
<span>
{{ message.messageText }}
</span>
</div>
</div>
</div>

如果 JSON 是初始的 myConversations,那么您将不需要对该数据执行任何操作,因为它已经足够使用了。

关于json - 如何在 Angular 中基于外部 NgFor 建立内部 NgFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55250268/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com