我正在尝试在Angular中解析JSON对象,但无法正常工作。在我的服务中,我创建了一个json对象并粘贴了所有数据。在组件中,我尝试解析此json并在youSend.message中显示所有消息。
我要在component.html中显示youSend的所有消息
jsonDATA
[
{
"name": "Valentyn",
"email": "fr@fr.fr",
"mobile": "0650004641",
"code_postale": "78000",
"messages": [
{
"youSend": [
{ message: "Hello, how much this PC?"},
{ message: "Ok, I want by"},
{ message: "Thanks for your answers"},
],
"forYouSend": [
{ message: "Hello, this PC 1499"},
{ message: "Ok, I prepare your order"},
{ message: "Thanks for your"},
]
}
],
"orders": [
{
"object": "MSI Ge62VR Apache Pro",
"price": 1499
},
{
"object": "Samsung S9",
"price": 899
}, {
"object": "Qnap-TS251+",
"price": 499
}
]
}]
file.servive.ts
public users: [] = [{***jsonDATA***}]
public allUsers: [] = [];
constructor() { }
public getUsers() {
return this.users.map(data => this.allUsers = data);
}
file.component.ts
users: [] = [];
msgUserSend: [] = [];
constructor( private papafils: PapafilsService ) { }
ngOnInit() {
this.users = this.papafils.getUsers();
this.msgUserSend = this.users.map(b => {
return b.messages;
});
file.component.html
<div *ngFor="let user of users">
<h4 class="nameColor">{{ user.name }}</h4>
<div *ngFor="let msg of user.messages">
{{ msg.youSend.message }}
</div>
<div *ngFor="let userOrder of user.orders" class="userOrders">
{{ userOrder.object }} and {{ userOrder.price }}
</div>
答案 0 :(得分:0)
youSend是一组消息,因此您不能直接使用msg.youSend.message
要显示一系列消息,您可以尝试
<h4 class="nameColor">{{ user.name }}</h4>
<div *ngFor="let msg of user.messages">
{{ msg.youSend |json }}
</div>
<div *ngFor="let userOrder of user.orders" class="userOrders">
{{ userOrder.object }} and {{ userOrder.price }}
</div>
</div>
答案 1 :(得分:0)
您需要另一个循环:
<div *ngFor="let user of users">
<h4 class="nameColor">{{ user.name }}</h4>
<div *ngFor="let msg of user.messages">
<div *ngFor="let m of msg.youSend">
{{ m.message }}
</div>
</div>
<div *ngFor="let userOrder of user.orders" class="userOrders">
{{ userOrder.object }} and {{ userOrder.price }}
</div>
</div>
答案 2 :(得分:0)
因为消息是一个包含1个项目的数组,所以您需要使用messages[0]
来访问yousend
属性。
<div *ngFor="let msg of user.messages[0].youSend">
{{ msg.message }}
</div>