You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中setInterval调用getDrinks报Cannot read properties of undefined错误

Angular定时更新mat-table报错的原因及解决方案

问题原因

你遇到的核心问题是**setInterval调用组件方法时丢失了this上下文**:
当你执行setInterval(this.getDrinks, 5000)时,传递给setInterval的是getDrinks函数的原始引用,此时函数内部的this不再指向PrijslijstComponent实例,而是全局对象(浏览器环境下为window)。这就导致getDrinks里访问this.drinksService时,this是undefined,直接抛出“Cannot read properties of undefined”错误,同时因为this.drinksService不存在,getDrinksByGroup根本不会执行,所以你看不到对应的日志。

快速修复方案

方案1:用箭头函数绑定上下文

通过箭头函数包裹getDrinks调用,让this继承当前组件的上下文:

ngOnInit(): void {
  this.getDrinks();
  this.interval = setInterval(() => this.getDrinks(), 5000);
}

方案2:用bind强制绑定this

直接把getDrinks的this绑定到组件实例:

ngOnInit(): void {
  this.getDrinks();
  this.interval = setInterval(this.getDrinks.bind(this), 5000);
}

更符合Angular生态的定时更新方案

Angular项目推荐使用RxJS的interval操作符实现定时任务,它和响应式架构更契合,还能自动管理订阅避免内存泄漏:

步骤1:导入必要的RxJS操作符

在prijslijst.component.ts顶部添加:

import { interval, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

步骤2:添加组件销毁信号

在组件类中定义一个用于终止订阅的Subject:

export class PrijslijstComponent {
  // ... 其他已有属性
  private destroy$ = new Subject<void>();
  
  // ... 其他方法
}

步骤3:用RxJS实现定时任务

修改ngOnInit和ngOnDestroy:

ngOnInit(): void {
  this.getDrinks();
  // 每5秒触发一次数据更新,组件销毁时自动停止
  interval(5000)
    .pipe(takeUntil(this.destroy$))
    .subscribe(() => this.getDrinks());
}

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

优化mat-table更新逻辑

每次创建新的MatTableDataSource不是最优解,可直接更新现有数据源的data属性,减少不必要的对象创建:

getDrinks() {
  console.log('Getting drinks')
  this.drinksService
      .getDrinksByGroup()
      .subscribe(({alcohols, notAlcohols}) => {
        if(alcohols !== undefined) {
          this.alcohols = alcohols;
        }
        if(notAlcohols !== undefined) {
          this.nonAlcohols = notAlcohols;
        }
        // 复用已有的数据源实例
        if (this.dataSourceAlcohol) {
          this.dataSourceAlcohol.data = this.alcohols;
        } else {
          this.dataSourceAlcohol = new MatTableDataSource(this.alcohols);
        }
        if (this.dataSourceNonAlcohol) {
          this.dataSourceNonAlcohol.data = this.nonAlcohols;
        } else {
          this.dataSourceNonAlcohol = new MatTableDataSource(this.nonAlcohols);
        }
  });
}

内容的提问来源于stack exchange,提问作者JasperR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:28:15