setTimeout 方法混淆了 Angular 17 应用程序中“this”关键字的范围

问题描述 投票:0回答:1

我正在尝试实现一个功能与秒表几乎相同的动画。在我的组件中,我有一个如下所示的函数

private count():void{
    const currentYear : number = new Date().getFullYear();
    /*const exp : number = this.Data ? currentYear - this.Data : 0;*/

    /* this is just for testing purpose but the commented line above is what
    I'd actually like to work with*/
    const exp : number = 23;

    for(let i = 0; i < exp; i++){
      setTimeout(()=>{

        //this is a variable defined on my component
        this.Experience++;
      }, 30);
    }
}

当我注释掉

setTimeout()
方法时,
Experience
变量会递增,但是当我将其添加回页面时,它就会停止,就像陷入无限循环一样。我研究了
setTimeout()
方法并注意到文档说这个

当您将方法传递给 setTimeout() 时,将使用可能与您期望不同的 this 值来调用该方法。

读完后,我假设在组件上定位

this.Experience
一定会混淆
setTimout()
方法,因为它可能在自己的范围内搜索变量而不是组件的范围。有谁知道我如何解决这个问题或以其他方式实现此功能?

angular
1个回答
0
投票

for 循环内部有一个

setTimeout
,因此循环会创建很多异步操作,这些操作会在同步代码完成后执行。理想情况下它应该可以工作,但是异步任务会立即执行,因此这可能就是您遇到此问题的原因!最好选择
setInterval
,它基本上做同样的事情,一旦满足中断条件,您就可以清除间隔!

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div class="exp-box">
        {{Experience}}
    </div>
  `,
  styles: [
    `
  .exp-box {
    height:100px;width:100px;background-color: black; color: white;
    display: flex;align-items: center;justify-content: center;font-weight:50px;
    border-radius: 15px;
  }
  `,
  ],
})
export class App {
  Experience = 0;
  Data = 2014;

  ngOnInit() {
    this.count();
  }

  private count(): void {
    const currentYear: number = new Date().getFullYear();
    const exp: number = this.Data ? currentYear - this.Data : 0;
    let i = 0;
    const intervalRef = setInterval(() => {
      this.Experience++;
      if (i > exp) {
        clearInterval(intervalRef);
      }
      i++;
    }, 30);
  }
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.