如何用另一个函数覆盖 NgOnit 中的一个函数?

How to Override a function in NgOnit by another function?

我在 NgOnit() 中调用了两个函数 startTimer()。我还有另一个功能 stopTimer(),我希望它在定时器达到 ('00:00') 时工作。我尝试将 this.stoptimer() 函数放在 NgOnit 和构造函数中,但它覆盖了 startimer() 函数。如果我把它放在 class 之外,我会得到一个错误 error TS1068: Unexpected token. A constructor, method, accessor, or property was expected. 我在想我要么需要以不同的方式调用 stoptimer(),要么我需要将它放在构造函数的 if 语句中,但我不知道如何调用时间 属性 time: BehaviorSubject<string> = new BehaviorSubject('01:00');

export class Pagename implements OnInit {
  sub: any;

  time: BehaviorSubject<string> = new BehaviorSubject('01:00');

  timer: number;
  interval;

  state: 'start' | 'stop' = 'stop';

 ngOnInit() {

    this.startTimer(1);
}
 startTimer(duration: number) {
   this.state = 'start';
   clearInterval(this.interval);
   this.timer = duration * 60;
   this.interval = setInterval( () => {
     this.updateTimeValue();
   }, 1000);

 }
 stopTimer() {
   clearInterval(this.interval);
   this.time.next('00:00');
   this.state = 'stop';

 }

 updateTimeValue() {
   let minutes: any = this.timer / 60;
   let seconds: any = this.timer % 60;

   minutes = String('0' + Math.floor(minutes)).slice(-2);
   seconds = String('0' + Math.floor(seconds)).slice(-2);

   const text = minutes + ':' + seconds;
   this.time.next(text);


   --this.timer;
 }
}
updateTimeValue() {
    let minutes: any = this.timer / 60;
    let seconds: any = this.timer % 60;

    minutes = String('0' + Math.floor(minutes)).slice(-2);
    seconds = String('0' + Math.floor(seconds)).slice(-2);

    const text = minutes + ':' + seconds;
    this.time.next(text);

    --this.timer;
    // VVVVVVVVVVVV this is the change
    if (this.timer === 0) {
        this.stopTimer();
    }
}

或者,简称:

updateTimeValue() {
    let minutes: any = this.timer / 60;
    let seconds: any = this.timer % 60;

    minutes = String('0' + Math.floor(minutes)).slice(-2);
    seconds = String('0' + Math.floor(seconds)).slice(-2);

    const text = minutes + ':' + seconds;
    this.time.next(text);

    // decrement and check equality in the same line
    if (--this.timer === 0) {
        this.stopTimer();
    }
}

既然您已经在 "time" 属性 中使用行为主体,为什么不订阅对此值的更改,使用 tap 运算符,然后对其进行操作。这样您就可以将您的功能区域分开。

import { tap } from 'rxjs/operators';

this.time.pipe(
  tap( _time => {
    if (_time === '00:00') {
       this.stopTimer();
    }
  })
).subscribe();

您可以将它放在构造函数中或从另一个方法调用它。