繁体   English   中英

Angular NgFor问题

[英]Angular NgFor Issue

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

错误:找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到Iterables,例如数组。

以下是代码文件供参考。

`heroes.component.ts:

该文件已声明了heroes对象。

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> 

    模拟heroes.ts:

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

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

    你能在这里帮我吗?

  • ngFor不支持对象,请尝试以下操作:

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

    如错误所示

    找不到类型为“对象”的其他支持对象“ [对象对象]”

    您的英雄应该是数组而不是对象。 改成

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

    STACKBLITZ演示

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

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

    代替

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

    暂无
    暂无

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM