Angular17 中的倒计时器

问题描述 投票:0回答:1

我正在尝试在我的家庭组件中制作一个倒计时器。看起来有点像这样。

这是我在html文件中放置倒计时的地方:

<div>
  {{displayTime}}
</div>

我的Home.ts文件:

ngOnInit(): void {
  this.countdownSubscription = interval(1000).subscribe(val => this.countdownTimer(val));
}

countdownTimer(seconds: number) {
   const totalSeconds = Math.floor((this.targetDay - Date.now()) / 1000);
   const days = Math.floor(totalSeconds / (60 * 60 * 24));
   const hours = Math.floor((totalSeconds % (60 * 60 * 24)) / (60 * 60));
   const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
   const remainingSeconds = totalSeconds % 60;
   const formattedDays = days < 10 ? '0' + days : days;
   const formattedHours = hours < 10 ? '0' + hours : hours;
   const formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
   const formattedSeconds = remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds;
}

ngOnDestroy(): void {
   this.countdownSubscription.unsubscribe();
}

当我在控制台上登录时,它工作正常:

但是在我的本地主机:4200 上,它没有加载并且总是旋转:

即使在控制台或终端中,也不会出现任何错误:

谁能帮我解决这个问题,非常感谢!!!

angular countdown
1个回答
0
投票

你忘记了几件事:

 this.countdownSubscription = interval(1000).subscribe(val =>
         //here you give value to the variable "displayTime"
         this.displayTime=this.countdownTimer(val)
 );

countdownTimer(seconds: number) {
   ...
   //you need return something
   return formattedDays+":"+formattedHours+":"+formattedMinutes+":"+formattedSeconds
}

顺便说一句,您可以使用管道异步使 Angular 自动取消订阅

  countdownObs$!:Observable<string> //declare an observable

ngOnInit()
{
   //see that you **not** subscribe, simply transform the observable
   //using map
   this.countdownObs$= interval(1000).pipe(
       map(val =>this.countdownTimer(val))
    )
}

你使用

{{countdownObs$|async}}

管道异步管理取消订阅(不要忘记在组件/模块中导入 AsyncPipe 或 CommonModule)

© www.soinside.com 2019 - 2024. All rights reserved.