【问题标题】:Angular NgFor IssueAngular NgFor 问题
【发布时间】:2018-04-15 18:11:37
【问题描述】:

我正在尝试使用 NgFor 指令显示具有 id 和 name 的对象列表,但出现以下错误:

错误:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到数组等 Iterables。

以下是代码文件供参考。

`heroes.component.ts:

这个文件声明了英雄对象。

import { Component, OnInit } from '@angular/core';

  import { Hero } from '../hero';

  import { HEROES } from '../mock-heroes';
  @Component({
    selector: 'app-heroes',
    templateUrl: './heroes.component.html',
    styleUrls: ['./heroes.component.css']
  })

  export class HeroesComponent implements OnInit {   
    heroes = HEROES;
  }

heroes.component.html:

这是我在

中使用 NgFor 的文件
  • 标签。
     <ul class="heroes">
        <li *ngFor="let hero of heroes">
         <span class="badge">{{hero.id}}</span> {{hero.name}}
        </li>
      </ul>
    

    mock-heroes.ts:

    这个文件包含我想要在 UI 上显示的英雄的常量对象。

      import {Hero} from './hero';    
      export const HEROES: Hero[] ={        
        {id:11 , name:'Mr. Nice'},
        {id:12 , name:'Narco'},
        {id:13 , name:'Bombasto'}
      };
    

    你能帮帮我吗?

  • 【问题讨论】:

      标签: angular typescript


      【解决方案1】:

      如错误所示

      找不到不同类型的支持对象“[object Object]” '对象'

      你的英雄应该是一个数组而不是对象。改成,

      const HEROES: Hero[] =[
           {id:11 , name:'Mr. Nice'},
           {id:12 , name:'Narco'},
           {id:13 , name:'Bombasto'}
      ];
      

      STACKBLITZ DEMO

      【讨论】:

      • 谢谢萨吉塔兰。按照您的建议进行更改后,它现在正在工作。
      【解决方案2】:

      ngFor 不支持对象试试下面这个:

      export const HEROES: Hero[] =[
      
           {id:11 , name:'Mr. Nice'},
           {id:12 , name:'Narco'},
           {id:13 , name:'Bombasto'}
      ];
      

      【讨论】:

      • 嘿 Klodian 非常感谢您的帮助。经过您建议的更正后,它工作正常。
      【解决方案3】:

      您应该将 HEROES 定义为一个数组,使用 [ ] 而不是 { } 作为外部大括号:

      [
        { ... },
        { ... },
      ]
      

      而不是

      {
        { ... },
        { ... },
      } 
      

      【讨论】:

      • 嗨 Pac0 感谢您的回答和时间。它现在可以正常工作了。
      猜你喜欢
      • 2020-04-05
      • 2018-03-12
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多