【问题标题】:Ionic Runtime Error Cannot read property '0' of undefined离子运行时错误无法读取未定义的属性“0”
【发布时间】:2021-04-05 12:54:12
【问题描述】:

我在home.ts中的代码是这样的

schools: any;

 ionViewWillLoad(){

   this.afoDatabase.list('/students',
  {
    query:{
          orderByChild: 'department',
          equalTo: this.schools[0].department
        }
  }).subscribe(snap => {
    this.students = snap;
  });
  }

实际上变量 schools 在开始时并未设置为任何值。可以选择仅在页面加载后设置 schools 变量。 当我将 equalTo 的值硬编码为“xyz”而不是 this.schools[0].department 时,它按预期工作。

那么现在我应该如何构建查询,这样我就不会得到 ​​p>

运行时错误无法读取未定义的属性“0”

更新:

当我将学校声明更改为

schools: any[]=[];

我收到以下错误

无法读取未定义的属性“部门”

只要定义了值,那么只有我想要查询,否则我不想查询。这个条件怎么写?

【问题讨论】:

  • 应该是数组类型schools: any[ ] = [ ];
  • 如果将其声明为数组,则无法读取未定义的属性“部门”
  • 代码学校数组在哪里填充?是不是在ionViewWillLoad()之前
  • 没有。用户只能在页面加载后设置。
  • @vjnan369 您找到解决问题的方法了吗?我面临着类似的问题,如下所述。

标签: typescript firebase ionic-framework firebase-realtime-database ionic2


【解决方案1】:

我面临同样的问题(我正在学习 ionic )。我能够通过将函数调用同时放入ngOnInitionViewWillEnter 来解决它的唯一方法。当我声明数组时,我收到有关“标题”属性的错误。

当我从ngOnInit 中删除函数调用时,我收到错误:ERROR TypeError: Cannot read property '0' of undefined

我的例子很简单。我有一个服务,它有一个带有 getter 的私有数组来获取它的内容。我没有为我的示例进行任何数据库调用。

这是适合我的类型脚本代码。

  loadedPlaces: Place[];
  listedLoadedPlaces: Place[]; //for virtual scroll

  constructor(private placesService: PlacesService, private menuCntrl: MenuController) { }

  ngOnInit() {
    console.log('ngOnInIt');
    this.loadData();
  }

  ionViewWillEnter(){
    console.log('ionViewWillEnter');
    this.loadData();
  }

  loadData(){
    this.loadedPlaces = this.placesService.places; //getter property
    //for the virtual scroll
    this.listedLoadedPlaces = this.loadedPlaces.slice(1);
  }

我的环境

node: v14.15.5
npm: 6.14.11
angular: 11.2.0
ionic: 6.13.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    相关资源
    最近更新 更多