【问题标题】:How to watch a variable in angular component? [duplicate]如何观察角度分量中的变量? [复制]
【发布时间】:2020-05-11 17:32:27
【问题描述】:

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

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

如何正确地做到这一点?

这是代码的 sn-p -

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
  }
}

【问题讨论】:

  • 请贴出使用 elapsedTime 变量的方法。
  • 也请告诉我们您所面临的问题的更多信息。
  • 也显示一些代码 sn-p

标签: angular google-chrome-devtools augury


【解决方案1】:

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

要解决此问题,您可以从 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多