Angular 如何观察角度分量中的变量?
我有一个变量elapsedTime,在构造函数中初始化为Angular 如何观察角度分量中的变量?,angular,google-chrome-devtools,augury,Angular,Google Chrome Devtools,Augury,我有一个变量elapsedTime,在构造函数中初始化为0。我在ChromeDevTools调试器中以this.elapsedTime的形式查看它。它已正确初始化。我还在将使用此变量的方法中放置了一个断点 Angular继续,完成它的工作,加载不同的组件,监视的变量变成NaN。我想这个的上下文正在丢失 如何正确地做到这一点 下面是代码片段- import { Component, OnInit } from "@angular/core"; @Component({ selector: "
0
。我在ChromeDevTools调试器中以this.elapsedTime
的形式查看它。它已正确初始化。我还在将使用此变量的方法中放置了一个断点
Angular继续,完成它的工作,加载不同的组件,监视的变量变成NaN
。我想这个的上下文正在丢失
如何正确地做到这一点
下面是代码片段-
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
窗口
对象。并修改elapsedTime
并将其放在窗口
(此)对象中
要解决此问题,可以从setInterval的回调函数调用this.startTimer方法,如下所示
this.clock = setInterval(() => this.startTimer(), 1000);
或者将startTimer
功能更改为Arrow功能
,以保持此功能的完整性
startTimer = () => {
const currentTime = new Date().getTime();
// debugger;
this.elapsedTime = currentTime - this.startTime; // place breakpoint here
}
请发布使用elapsedTime变量的方法。还请告诉我们您面临的问题的更多信息。同时显示一些代码片段