我正试着在家里做一个倒计时器.它看起来有点像这样.

The countdown

以下是我在html文件中放置倒计时的位置:

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

我的home.ts文件:

ngOnInit(): void {
  this.countdownSubscription = interval(1000).subscribe(val => this.displayTime = 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;
   return formattedDays+":"+formattedHours+":"+formattedMinutes+":"+formattedSeconds
}

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

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

enter image description here

但在我的localhost:4200,它不加载,总是旋转:

enter image description here

即使在控制台或终端中,也不会出现类似的错误:

enter image description here

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

推荐答案

你忘记了几件事:

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

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

stackblitz分,两种方法都有

Angular相关问答推荐

根据Angular中的构建来卸载独立组件

如何在自定义验证器中获取所有表单控件(字段组动态创建)

为什么在回调完成之前,可观察对象会返回?

带独立零部件的TranslateLoader[Angular 16]

如何修复不允许的HttpErrorResponse 405?

使用指令的 Angular 自定义验证在 ng-change 中无法正常工作

如何处理后端删除元素后元素列表的刷新

有角.服务.模块构建失败.无法读取未定义的属性(读取文件)

Angular 在关闭另一个对话框后打开另一个对话框的最佳做法是什么?

手动关闭 SSE 连接:Angular

Angular 13 Sass 模块无法在编译中正确导入文件

如何将我的数组数据转换为逗号分隔的字符串

相对于根目录的 SCSS 导入

由router-outlet 创建时如何将css类应用于组件元素?

Angular2 + Jspm.io:使用类decorator 时需要反射元数据垫片

请求 http.GET 时发送的 Angular2 OPTIONS 方法

Angular2:如果 img src 无效,则显示占位符图像

缺少带有Angular的语言环境XXX的语言环境数据

如何使用无头浏览器运行测试?

Angular ngClass 和单击事件以切换类