问题出现的原因是setInterval的函数作用域与组件实例不同,因此需要使用箭头函数或将this存储在一个变量中并在函数中使用该变量来引用组件实例。
例如,如果有一个组件类:
export class MyComponent {
count = 0;
ngOnInit() {
setInterval(function() {
this.count++; // 这里的this不会引用到组件实例
}, 1000);
}
}
使用箭头函数解决该问题:
export class MyComponent {
count = 0;
ngOnInit() {
setInterval(() => {
this.count++; // 箭头函数会绑定到组件的上下文
}, 1000);
}
}
或者将this存储在一个变量中并在函数中使用该变量来引用组件实例:
export class MyComponent {
count = 0;
ngOnInit() {
const self = this;
setInterval(function() {
self.count++; // 使用self引用组件实例
}, 1000);
}
}