【问题标题】:Angular undefined attribut but it's not possible角度未定义的属性,但这是不可能的
【发布时间】:2018-10-04 18:22:30
【问题描述】:

我正在尝试使用 angular 获取本地 JSON 数据。 我的组件:

import { Component, OnInit } from '@angular/core';
import datalist from '../todolist.json';

console.log(JSON.stringify(datalist));
@Component({
  selector: 'app-todolist',
  templateUrl: './todolist.component.html',
  styleUrls: ['./todolist.component.css']
})
export class TodolistComponent implements OnInit {

  // will contain all data from ../todolist.json
  lists: any[];
  todolist: any;

  constructor() {}

  ngOnInit() {
    const test = Object.keys(datalist);
    for (const prop of test) {
      this.lists.push(datalist[prop]);
    }
  }
}

我得到这个错误:

ERROR TypeError: "this.lists is undefined"

我做错了什么?我真的不明白,当然,this.lists 是定义...

【问题讨论】:

  • lists: any[]=[];
  • 谢谢!我在 angular6 教程中看到了属性:没有“=[]”的任何 []...
  • 只有lists: any[] 你说它将是一个数组,但你没有给它一个值:没关系,只要你在尝试访问它之前给它一个值。

标签: angular typescript


【解决方案1】:

你需要如下初始化它

 lists: any[] = [];

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2016-05-18
    • 1970-01-01
    • 2019-07-04
    • 2021-01-21
    • 1970-01-01
    • 2015-08-10
    • 2021-01-24
    • 2021-01-06
    相关资源
    最近更新 更多