[英]I am trying to create a simple timer in Typescript, in the browser console it says "this.pad is not a function" and I don't get why
I am well aware this is not very Angular friendly, in fact I'd like to know from you a better fix to make it more "Angular-y" if possible, thank you.我很清楚这对 Angular 不是很友好,事实上我想从你那里知道一个更好的修复方法,如果可能的话,让它更“Angular-y”,谢谢。
export class TimerComponent implements OnInit {
min = 0;
sec = 0;
minutesLabel: any = document.getElementById('minutes');
secondsLabel: any = document.getElementById('seconds');
startTimer() {
const interval = setInterval(this.setTime, 1000);
return interval;
}
setTime() {
++this.sec;
var r: any = this.sec / 60;
this.secondsLabel.innerHTML = this.pad(this.sec % 60);
this.minutesLabel.innerHTML = this.pad(parseInt(r));
}
pad(val: any) {
var valString = val + '';
if (valString.length < 2) {
return '0' + valString;
} else {
return valString;
}
}
constructor() {}
ngOnInit() {}
}
You have a few solutions here:您在这里有一些解决方案:
setInterval(this. setTime.bind(this), 1000);
or:或者:
setInterval(() => this.setTime(), 1000);
The reason being that when you pass setTime
into setTimeout
, the this
scope of your object instance isn't preserved.原因是当您将setTime
传递到setTimeout
,不会保留对象实例的this
范围。
Here is a answer that also makes it as you said "Angular-y".这是一个答案,正如您所说的“Angular-y”。
This makes use of rxjs timer which is similar to setTimeout but more configurable, form prod use you will need some way to unsubscribe on destroy.这利用了 rxjs 计时器,它类似于 setTimeout 但更可配置,表单 prod 使用您需要某种方式在销毁时取消订阅。
I also simplified a lot here that was not needed, as well as added better type definitions.我还在这里简化了很多不需要的东西,并添加了更好的类型定义。
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
minutesLabel: string;
secondsLabel: string;
ngOnInit() {
timer(0, 1000).subscribe((sec) => {
this.secondsLabel = this._pad(sec % 60);
this.minutesLabel = this._pad(Math.floor(sec / 60));
});
}
private _pad(val: number) {
var valString = val + '';
if (valString.length < 2) {
return `0${valString}`;
} else {
return valString;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.