首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular12插值自动更新

Angular12插值自动更新
EN

Stack Overflow用户
提问于 2021-07-01 03:39:22
回答 2查看 39关注 0票数 1

我有一个从socket.io服务器接收数据(一个非常基本的计时器)的Angular12应用程序。此数据应随着计时器的增加而在UI上自动更新。我使用插值来显示"time= new Date(0,0,0,0,0,0,0,0).变量在component.ts中更新,但我的UI没有更新,它停留在00:00:00。我如何才能使我的变量“->”(-> component.ts)在我的UI上自动更新?

Component.ts:

代码语言:javascript
复制
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs';
import { WebsocketService } from './websocket.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'timerServiceClient';
  time = new Date(0,0,0,0,0,0);
  laps = [""];
  startbtnDisabled = false;


  constructor(private webSocketService: WebsocketService){}

  ngOnInit() {
    this.webSocketService.listen('connectmsg').subscribe((data) => {
      console.log(data)
    })
  }

  onStartTimer() {
    const message = 'Start the timer'
    this.webSocketService.emit('startTimer', message)
    this.startbtnDisabled = true
    this.webSocketService.listen('timer').subscribe((data: number) => {
      console.log(data)
      this.time.setSeconds(data);
    })
  }

  onStopTimer() {
    const message = 'the timer has stopped'
    this.webSocketService.emit('stopTimer', message)
    this.startbtnDisabled = false
  }

  onResetTimer(){
    const message = 'Reset the timer'
    this.webSocketService.emit('resetTimer', message)
  }

component.html:

代码语言:javascript
复制
<div class="container">

<div id="timerDisplay">
  <span >
  <h1>{{time | date: 'HH:mm:ss'}}</h1>
  </span>
</div>

<hr>
<div class="buttons">
<button mat-raised-button color="primary" disabled="{{startbtnDisabled}}" (click)="onStartTimer()" >Start</button>
<button mat-raised-button color="primary" (click)="onStopTimer()">Stop</button>
<button mat-raised-button color="warn" (click)="onResetTimer()">Reset</button>
<button mat-raised-button color="accent" (click)="onRegisterLap()">Lap</button>
</div>

<mat-list>
  <mat-list-item *ngFor="let lap of laps">{{lap}}</mat-list-item>
</mat-list>
</div>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-07-01 03:48:54

您可能需要“设置”时间变量。

代码语言:javascript
复制
onStartTimer() {
    const message = 'Start the timer'
    this.webSocketService.emit('startTimer', message)
    this.startbtnDisabled = true
    this.webSocketService.listen('timer').subscribe((data: number) => {
      console.log(data)
      this.time = new Date(this.time.setSeconds(data)); <- SET TIME TO THE NEW VALUE
    })
  }
票数 0
EN

Stack Overflow用户

发布于 2021-07-01 03:54:51

你需要在Brian回答的时候更新你的属性时间。

此外,更好的方法是创建一个新的Date实例,而不是设置秒:

代码语言:javascript
复制
this.time = new Date(secondsReceivedFromWEbSocket);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68200736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档