【问题标题】:Angular2 *ngFor: "Cannot read property '0' of undefined"Angular2 *ngFor:“无法读取未定义的属性‘0’”
【发布时间】:2017-01-13 14:45:06
【问题描述】:

我试图从 JSON 文件中获取数据以构建表单。

这是我的模板的一部分:

  <div class="form-group">
    <label for="power">Power</label>
    <select class="form-control" id="power" required>
      <option *ngFor="let p of heroes" [value]="p.level">{{p.level}}</option>
    </select>
  </div>

这是远程 JSON 文件的一部分:

{
    "data": [
        {
            "level": "newbie",
            "places": [
                {
                    "place": "earth",
                    "categories": [
                        {
                            "category": "human",
                            "values": [
                                ...

它没有问题,我在select 菜单中得到newbie 和其他选项。 但我想在地方循环,所以我以这种方式编辑 html 模板:

  <div class="form-group">
    <label for="power">Power</label>
    <select class="form-control" id="power" required>
      <option *ngFor="let p of heroes[0].places" [value]="p.place">{{p.place}}</option>
    </select>
  </div>

这是我用来从 JSON 文件中获取数据的服务:

@Injectable()
export class HeroService {
    private url = 'app/mockups/heroes.json';

    constructor(private http: Http) { }

    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.url)
            .toPromise()
            .then(response => response.json().data as Hero[])
            .catch();
    }
}

这里是hero.component

export class HeroComponent implements OnInit {
    heroes: Hero[];

    constructor(private heroService: HeroService) { }

    ngOnInit():void {
        this.getHeroes();
}

    getHeroes(): void {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

但我得到 “无法读取未定义的属性 '0'” 错误。

为什么?

【问题讨论】:

    标签: arrays json object angular ngfor


    【解决方案1】:

    我发现了问题所在。我收到此错误是因为我正在异步获取数据,并且当 Angular 第一次尝试解析绑定时数据仍然为空,因此 heroes[0] 失败。

    所以我解决了初始化heroes数组并使用“猫王运算符”的问题:

    heroes: Hero[]; 而不是组件中的heroes: Hero[] = [];

    heroes[0]?.places 代替 html 模板中的heroes[0].places

    【讨论】:

    【解决方案2】:

    替代@Gunter Zochbauer 的解决方案,您可以将heroesas 声明为合适类型的数组属性。如果您有任何具有heroes 的所有属性的类,您将heroes 属性声明为:

    heroes:Array<Heroes> //Assuming class name is Heroes
    

    并在构造函数中初始化如下:

    constructor(){
    ...    
    this.heroes=new Array<Heroes>();
    }
    

    在您的 ngFor 循环中,只需按如下方式访问类属性:

    <option *ngFor="let p of heroes" [value]="p.place">{{p.place}}</option>
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      我猜你想要的是什么

      *ngFor="let p of heroes?.data"
      

      因为heroes 似乎是一个对象,而ngFor 只能迭代数组。 level 属性也在一个数组项中。

      【讨论】:

      • 是的,html 模板中的 heroesdata 数组上循环。现在我想循环data[0].places数组,其中[0]data数组的第一个对象。
      • 这在您的问题中并不明显。我猜这个错误是由将json分配给heroes的代码引起的。
      • 根据您的更新“是的,html 模板中的英雄在数据数组上循环。”似乎不是真的。您是否尝试过我答案中的代码?
      • 是的,我在 data 数组上循环,因为我可以在输出中看到项目。我从服务中得到它 (.then(response =&gt; response.json().data as Hero[]))。因此,您的代码不起作用。
      • 那么您在问题中提出的 JSON 并不完全是您分配给 heroes
      猜你喜欢
      • 1970-01-01
      • 2017-12-15
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多