我有这个JSON,我需要显示所有数据,如下所示:
res {
"StatusCode": 0,
"StatusMessage": "OK",
"StatusDescription": [
{
"sensors": [
{
"serial": "sensor1",
"id": "1"
},
{
"serial": "sensor2",
"id": "2"
},
{
"serial": "sensor3",
"id": "3"
}
],
"HBP_id": "12",
"HB_id": "123",
"serial_number": "hb1",
"note": "test"
},
{
"sensors": [
{
"serial": "sensor4",
"id": "4"
},
{
"serial": "sensor5",
"id": "5"
},
{
"serial": "sensor6",
"id": "6"
}
],
"HBP_id": "23",
"HB_id": "234",
"serial_number": "hb2",
"note": "test"
},
{
"sensors": [
{
"serial": "sensor7",
"id": "7"
},
{
"serial": "sensor8",
"id": "8"
}
],
"HBP_id": "34",
"HB_id": "345",
"serial_number": "hb3",
"note": "test"
}
]
}
我想在html Nativescript中显示这些数据:
序列号: hb1
传感器: 传感器1 传感器2 传感器3
序列号: hb2
传感器: 传感器3 传感器4 传感器5
序列号: hb3
传感器: 传感器7 sensor8
我尝试了这段代码,但是有了它我只能显示第一个数据:
<ListView [items]="items" (itemTap)="onItemTap($event)">
<ng-template let-item="item" let-i="index" let-odd="odd" let-even="even">
<StackLayout [class.odd]="odd" [class.even]="even">
<Label [text]="item.serial_number"></Label>
<Label *ngFor="let subItem of item?.sensors" [text]="subItem.serial"></Label>
</StackLayout>
</ng-template>
</ListView>
component.ts:
public items: Items[];
constructor(private service: ItemsService) {
}
public ngOnInit() {
this.getallitems();
}
getallitems() {
this.service.itemsGetAll().subscribe(
items=> {
console.log('itemsfrom ws',items) // show all
this.items= items;
}
);
}
service.ts
public itemsGetAll(): Observable<Items[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.itemsGetAll), {
headers: headers
})
.pipe(map((response: Response) => {
console.log('response', response)
let res = response.json();
if (res.StatusCode === 1) {
} else {
return res.StatusDescription.map(hbp => {
return hbp;
});
}
}))
}
显示:
序列号: hb1
传感器: 传感器1 传感器2 传感器3
您能问我,如何在项目中使用* ngFor吗?有什么想法吗?
更新: 我这样更改我的html:
<StackLayout [class.odd]="odd" [class.even]="even">
<Label *ngFor="let item of items" [text]='"[" + item.serial_number +"] " + item?.sensors'></Label>
</StackLayout>
答案 0 :(得分:0)
您应该更改为此:
Term
其余代码相同!
答案 1 :(得分:0)
您可以尝试此解决方案
public items: Items[];
constructor(private service: ItemsService) {
}
public ngOnInit() {
this.getallitems();
}
getallitems() {
this.service.itemsGetAll().subscribe(
items=> {
console.log('itemsfrom ws',items) // show all
this.items= items.StatusDescription;
}
);
}