【问题标题】:problem api-- Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays问题 api--找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2021-01-17 17:27:55
【问题描述】:

我得到这个 api “http://dummy.restapiexample.com/api/v1/employees” 然后我尝试将它与 *ngFor 一起使用,但发生了这个问题 “ERROR 错误:找不到类型为‘object’的不同支持对象‘[object Object]’。NgFor 仅支持绑定到 Iterables,例如数组。”

app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  employes;
  constructor(private http : HttpClient) { 
    this.http.get('http://dummy.restapiexample.com/api/v1/employees').subscribe(employ =>
{this.employes = employ})
  }
}

app.component.html

<table class="table">
    <thead class="thead-dark">
      <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Salary</th>
        <th scope="col">Age</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor='let empo of employes ; let i = index '>
        <th scope="row">{{i + 1}}</th>
        <td>{{empo.employee_name}}</td>
        <td>{{empo.employee_salary}}</td>
        <td>{{empo.employee_age}}</td>
      </tr>
    </tbody>
  </table>

【问题讨论】:

  • 这里可能有一些问题; 1.您不会将“employes”作为数组启动,因此它将是“未定义”的。 2. 你是否验证了对 api 调用的响应实际上返回了一个 'employes' 数组?即'employ'实际上是否返回一个数组?

标签: angular


【解决方案1】:

您的回复如下所示:

{ status: string, data: [], message: string }

所以你有两个选择:

在构造函数中 {this.employes = employ.data}

在模板视图中 &lt;tr *ngFor='let empo of employes.data ; let i = index '&gt;


如果 API 响应成功,其中一项必须有效

你最好把你的 http 请求移到 OnInit 方法中, 所以你的组件应该是这样的:

export class AppComponent implements OnInit {

 employes;

 constructor(private http: HttpClient) {}

 ngOnInit(): void {
  this.http.get('http://dummy.restapiexample.com/api/v1/employees')
   .subscribe(res => this.employes = res.data);
 }
}

【讨论】:

  • src/app/app.component.ts:12:61 中的错误 - 错误 TS2339:“对象”类型上不存在属性“数据”。 12 empServices.get().subscribe(act=> this.Activities = act.data);这个消息出现在终端是什么?主要问题已解决,但出现此消息
猜你喜欢
  • 2017-02-10
  • 2018-10-29
  • 2019-04-04
  • 2020-10-17
  • 2017-10-15
  • 2019-05-12
  • 2019-01-31
  • 2018-07-19
相关资源
最近更新 更多