【问题标题】:[solved]unable to fetch the data form data array. What is the issue?[已解决]无法从数据数组中获取数据。问题是什么?
【发布时间】:2020-07-20 17:35:11
【问题描述】:

我的服务代码:

export class RecordService {

  constructor() { }

  getData(){
    return [
      {
        name : "Mim",
        online : true
      },
      {
        name : "ABC",
        online : false
      },
      {
        name : "XYZ",
        online : true
      },
      {
        name : "ABC",
        online : false
      },
      {
        name : "XYZ",
        online : true
      }
    ]
     
  }
}

app.component.ts 代码:

export class AppComponent {
  // text = 'intro2angular'
  data = {}

  constructor(private myFirstService : RecordService){

  }
  
  ngOninit(){
    this.data = this.myFirstService.getData()
  } 

我的 app.component.html 代码:

<table>
  <tr>
    <td>S.no</td>
    <td>name</td>
    <td>isonline</td></tr>
  <tr *ngFor="let record of data; let i = index; let firstRecord = first; let lastRecord = last; let evenrecord = even; let oddrecord = odd" [ngClass]="{odd: oddrecord, even: evenrecord, first:firstRecord, last:lastRecord}">
    <td>{{i + 1}}</td>
    <td>{{record.name}}</td>
    <td>{{record.online}}</td>
  </tr>
</table>

无法从数据数组中获取数据。给出错误错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays。有什么问题?

另一个错误给出: 错误上下文 DebugContext_ {view: {…}, nodeIndex: 10, nodeDef: {…}, elDef: {…}, elView: {…}}。有什么问题?

【问题讨论】:

    标签: angular


    【解决方案1】:

    data 初始化为空数组而不是空对象。

    export class AppComponent {
      data = [];        // <-- array here
    
      constructor(private myFirstService : RecordService) { }
    
      ngOninit() {
        this.data = this.myFirstService.getData();
      }
      
      ...
    }
    

    当组件被渲染时,在ngOnInit被触发之前,data变量持有一个空对象而不是一个数组。 *ngFor 指令默认不能循环对象。

    更新

    工作示例:Stackblitz

    【讨论】:

    • 做了数据 = [ ];但获取的数据不显示在浏览器中
    • @develop_code:你使用什么变化检测策略?
    • 我正在使用 Angular 并且在 localhost 中没有看到任何输出表数据
    • @develop_code:Angular 中的change detection mechanism 根据控制器中的更改决定何时重新渲染模板。假设您使用的是默认机制,则应该呈现推送到 data 的新值。我已更新答案以包含 Stackblitz。
    • 在 Stackblitz 上,输出显示非常好。什么不是角度?
    猜你喜欢
    • 2019-08-02
    • 2019-09-27
    • 1970-01-01
    • 2021-09-14
    • 2021-10-15
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多