我有一个从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:
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:
<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>发布于 2021-07-01 03:48:54
您可能需要“设置”时间变量。
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
})
}发布于 2021-07-01 03:54:51
你需要在Brian回答的时候更新你的属性时间。
此外,更好的方法是创建一个新的Date实例,而不是设置秒:
this.time = new Date(secondsReceivedFromWEbSocket);https://stackoverflow.com/questions/68200736
复制相似问题