如何查看 angular 组件中的变量?

How to watch a variable in angular component?

我有一个变量 elapsedTime,在构造函数中初始化为 0。我在 Chrome devtools 调试器中以 this.elapsedTime 的形式观看它。它已正确初始化。我还在将使用此变量的方法中放置了一个断点。

Angular 继续,做它的事情,加载不同的组件,观察变量变成 NaN。我想 this 的上下文正在丢失。

如何正确执行此操作?

这是代码片段 -

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-game-control",
  templateUrl: "./game-control.component.html",
  styleUrls: ["./game-control.component.css"]
})
export class GameControlComponent implements OnInit {
  startTime: number;
  elapsedTime: number;
  clock: any;
  constructor() {
    this.startTime = new Date().getTime();
    this.elapsedTime = 0; // Correctly displays as initialized to 0 in watch variables
    this.clock = setInterval(this.startTimer, 1000);
  }

  ngOnInit() {}

  startTimer() {
    const currentTime = new Date().getTime();
    // debugger;
    this.elapsedTime = currentTime - this.startTime; // place breakpoint here
  }
}

这似乎是上下文 (this) 的问题,因为您通过传递其引用直接调用了 this.startTime 函数。由于您在 setInterval 中传递了 this.startTime 的引用,因此它被视为 this 作为 window 对象。并修改 elapsedTime 并将其放入 window(this) object.

要解决此问题,您可以从 setInterval 的回调函数中调用 this.startTimer 方法,如下所示。

this.clock = setInterval(() => this.startTimer(), 1000);

或将 startTimer 函数更改为 Arrow function 以保持 this 完整。

startTimer = () => {
    const currentTime = new Date().getTime();
    // debugger;
    this.elapsedTime = currentTime - this.startTime; // place breakpoint here
}

Working Demo