首页 > 解决方案 > Angular7 - 尝试根据从 api 接收的内容创建表。错误:无法读取未定义的属性“StoreLogId”

问题描述

我正在尝试根据我从 api 接收的 json 创建一个角度表。但我收到此错误:

无法读取未定义的属性“StoreLogId”

这是我得到的 json(我正在使用的列表值):

[{storeLogId: 18, storeId: 2, userId: 10, ip: "192.168.1.15", logType: 1},{storeLogId: 15, storeId: 2, userId: 10, ip: "192.168.1.15", logType: 1}]

这是我想在其中显示表格的 html:

 <div class="table-responsive">
    <table class="table table-striped table-sm">
      <thead>
        <tr>
          <th>StireLogId</th>
          <th>StoreId</th>
          <th>UserId</th>
          <th>LogType</th>
          <th>LogTtext</th>
          <th>CreatedTime</th>
        </tr>
      </thead>
      <tbody>

        <tr *ngFor="let response of logsList ; let i = index">
            <td>{{response[i].StoreLogId}}</td>
            <td>{{response[i].StoreId}}</td>
            <td>{{response[i].UserId}}</td>
            <td>{{response[i].LogType}}</td>
            <td>{{response[i].LogTtext}}</td>
            <td>{{response[i].CreatedTime}}</td>
    </tbody>
    </table>
  </div>

这是我从中获取数据的服务类:

export class HomeComponent implements OnInit {
  messageForm: FormGroup;
  submitted = false;
  success = false;
  logsList ;

  constructor(private data: DataService , private formBuilder: FormBuilder ) { }

  public ngOnInit(): void  {
    this.data.getAllData(1).subscribe(data => {
      this.logsList = data['obj'];
      console.log(data["obj"]);
    });
    }
}

标签: angular

解决方案


您非常接近尝试编辑以下内容。假设您在问题中添加的 JSON 来自console.log()订阅中的,您的模板应如下所示。

解决方案

<tbody>
  <table>
    <tr *ngFor="let response of logsList ; let i = index">
      <td>{{response.StoreLogId}}</td>
      // other <td> will look the same just changing the accessing value.
  </table>
</tbody>

解释

*ngFor用于访问值时无需添加索引。查看有关显示数据的Angular 文档。您仍然可以*ngFor通过索引运行,这可以用来轻松地将数组中元素的索引传递给函数和其他有用的东西。BR。


推荐阅读