簡體   English   中英

如何將多個對象 json 數據操作到 angular 8 中的表中

[英]How to manipulate multiple object json data into table in angular 8

我有一個簡單的 json 數據,我需要根據條件將它填充在表上。我可以填充,但只有第一個對象正在呈現。 我的json數據就像

{ "3": {"test": {"id":1, "name":"cat"}},
  "4": {"test": {"id":2, "name":"dog"}}
}

誰能幫幫我嗎?

這是我的代碼:

主頁.component.html

<div>
    <table border="1" cellspacing="2">
        <tr *ngFor = "let x of data2">
            <td>{{x.id}}</td>
            <td>{{x.name}}</td>
        </tr>
    </table>
</div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';

declare var $: any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    imageSource :any;
    statusdata1: any;
    statusdata2:any;
    closeResult: string;
    registerForm: FormGroup;
    submitted = false;
    webSocketEndPoint: string = 'wss://echo.websocket.org/';
    topic: string = "/topic/greetings";
    stompClient: any;
    mySocketData:any;
    data1:any = [];
    data2:any = [];

    constructor(private modalService: NgbModal,private formBuilder: FormBuilder) {}

    ngOnInit() {
        let statusdata2 = {"3":{"test":{"id":1,"name":"cat"}},"4":{"test":{"id":2,"name":"dog"}}}

        if(statusdata2[3]) {
            this.data2.push(statusdata2[3].test);
            console.log(statusdata2);
        }
    }
}

在您的 HTML 模板中,您正在對data2進行迭代

 <tr *ngFor = "let x of data2">
 <td>{{x.id}}</td>
 <td>{{x.name}}</td>

這意味着x應該是這樣的(根據你的代碼):

 let statusdata2 = {"3":{"test":{"id":1,"name":"cat"}},"4":{"test":{"id":2,"name":"dog"}}}; console.log('data2', statusdata2[3]);

這意味着,而不是x.id實際需要x.test.id name 你想要x.test.name而不是x.name

試試這個:

 <tr *ngFor = "let x of data2">
 <td>{{x.test.id}}</td>
 <td>{{x.test.name}}</td>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM