【问题标题】:how to access a json in a json in a array with ngfor如何使用 ngfor 访问数组中的 json 中的 json
【发布时间】:2018-10-01 22:19:05
【问题描述】:

我使用 Angular 6 和 Firebase。我想显示所有约会的列表。以下是我的操作方式。

service.ts

getRDV() {
  this.rdvList = this.firebase.list('/rdv');
  return this.rdvList;
}

型号:

export class RDV {
  key: string;
  date: string;
  heure: string;
  spe: string;
  uidpat: string;
  uid: string;
  status: string;
}

在 ts 中:

export class ListComponent implements OnInit {

  rdvList: RDV[];

  constructor(
    private usersService: UsersService,
    private router: Router
  ) {}

  ngOnInit() {
    var x = this.usersService.getRDV();
    x.snapshotChanges().subscribe(item => {
      this.rdvList = [];
      item.forEach(element => {
        var y = element.payload.toJSON();
        y["$key"] = element.key;
        this.rdvList.push(y as RDV);
      })
      console.log(this.rdvList)
    })
  }

}

在 HTML 中:

<tr *ngFor="let rdv of rdvList| myfilter:term, let i = index">
  <div *ngFor="let item of rdvList.rdv.key">
    <td> {{item.$key}} </td>
    <td> {{item.uidpat}} </td>
    <td> {{item.date}} </td>
    <td> {{item.heure}} </td>
    <td> {{item.spe}} </td>
    <td> {{item.uid}} </td>
    <td> 
      <button class="btn btn-primary" (click)="onViewUser(user?.uid)">
        Choisir
      </button> 
    </td>
  </div>
</tr>

数据结构:

实在是解决不了问题应该改怎么给他们推送到表里还是用模板*ngfor调整问题。

my JSON console.log

【问题讨论】:

  • 请在此处粘贴您的 json
  • ngOnit 中的 snapshotchanges(_) 是什么,为什么不直接从 x 订阅 result。例如。 this.getBenef() 从服务返回一个值,就像 getRDV() this.getBenef().subscribe( res => { this.benefaccountList = res['list']; ...... .....
  • 请在此处发布您的 json 响应
  • 这个错误是有道理的。你期待一份约会清单。但是您从/rdv 获取。这将在顶层有日期,并且在每个日期内,都会有约会对象。我个人觉得,由于每个约会对象中已经有一个日期字段,因此您不需要将每个约会添加到层次结构中。稍后您可以使用日期本身对其进行过滤。

标签: angular typescript firebase firebase-realtime-database


【解决方案1】:

显然你想要的只是嵌套在 DATE 键下方的约会对象列表。

如果你想提取所有这些约会对象,你必须像这样映射它们:

export class ListComponent implements OnInit {

  ...

  ngOnInit() {
    var x = this.usersService.getRDV();
    x.snapshotChanges().subscribe(item => {
      const appointments = [];
      item.forEach(element => {
        var y = element.payload.toJSON();
        y["$key"] = element.key;
        appointments.push(y);
      });

      // This is the operation
      this.rdvList = appointments
        .flatMap(item => Object.values(item))
        .filter(item => typeof item === "object");

      console.log(this.rdvList)
    })
  }

}

第一个flatMap 将从数组中的每个对象中提取所有值。这将包含您的约会对象以及日期字符串。

因此,您必须将filter 应用于第一个flatMap 操作映射的所有项目,以仅过滤掉Object 类型的项目

这应该会在rdvList 属性中为您提供约会对象,然后您可以使用*ngFor 在模板中循环访问它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多