簡體   English   中英

訪問嵌套 json object angular 6

[英]Access nested json object angular 6

我正在嘗試從 HTML 模板訪問嵌套數據,但我得到未定義或我沒有得到任何結果(沒有 class 列表或學生列表的空頁面)。

HTML 模板:

<div class="container">
        <label *ngFor="let class of listClass | keyvalue">
            <span> {{class.value.name}} </span>
        </label>

    <div>
        <label *ngFor="let student of class.students | keyvalue">
            <span>{{student.value.fullName}} </span>
        </label>
    </div>
</div>

這是獲取 class 和其中的學生列表的函數:

getListClasseStudent(){
        this.classService.getStudents().subscribe((data) => {
            this.listClass = data;
        });
    }

嵌套數據:

class:
0:{
   code: "Math01"
   teacher: 
      0: {id: 17551, name "Jack"}
   students: 
      0: {studentId: 1, fullName: "Patrick bob"}
      1: {studentId: 2, fullName: "Alice Alice"}
}
1:{
   code: "English01"
   teacher: 
      0: {id: 2, name "Nicolas"}
   students: 
      0: {studentId: 1, fullName: "Patrick bob"}
      1: {studentId: 2, fullName: "Alice Alice"}
}

我想訪問每個 class 的學生列表,有什么有效的方法嗎? 提前致謝。

<div class="container">
<div *ngFor="let c of listClass ">
    <label >
        <span> {{c.code}} </span>
    </label>
    <div>
        <label *ngFor="let student of c.students ">
        <span>{{student.fullName}} </span>
    </label>
    </div>
</div>

試試這個(沒有你的管道的例子)

'Class' object 沒有屬性 'value.name' (可能會由您的 pipe '| keyvalue' 注入)。 第二個 *ngFor 不需要在第一個內部,因為他需要在每個 class 內部迭代一個學生數組。

我希望這有幫助。

創建一個 pipe 如下所示

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
    transform(value: Object): Array<string> { return Object.keys(value); }
}

在 app.module.ts 中導入上述 pipe 並在 html 頁面中使用 pipe 如下所示

 <div *ngFor="let key of questions | ObjNgFor" class="row">

    {{ questions[key].name}}

<div *ngFor="let r of questions[key].sub_sections | ObjNgFor ; let indx=index" 
   class="card-body"> 

{{ questions[key].sub_sections[r].name }}"

</div>

這個例子應該工作

暫無
暫無

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

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