在此示例中,我使用了倒数计时器解决方案:Stackblitz ---来自对此question.的接受答案
区别是我不使用html输入重置计时器,而是这样的Websocket消息(不同之处在于开关):
turn-timer.directive.ts:
@Directive({
selector: '[counter]'
})
export class CounterDirective implements OnChanges, OnDestroy {
private counter$ = new Subject<any>();
private countSub$: SubscriptionLike;
@Input() counter: number;
@Input() interval: number;
@Output() value = new EventEmitter<number>();
constructor(private client: ClientService)
{
this.countSub$ = this.counter$.pipe(
switchMap((options: any) =>
timer(0, options.interval).pipe(
take(options.count),
tap(() => this.value.emit(--options.count))
)
)
).subscribe();
this.client.messages.subscribe(msg =>
{
switch (msg.SUBJECT)
{
case 'TT_UPDATE':
{
this.counter = msg.COUNTER;
}
break;
default:
break;
}
});
}
ngOnChanges() {
this.counter$.next({ count: this.counter, interval: this.interval });
}
ngOnDestroy() {
this.countSub$.unsubscribe();
}
}
那根本没有重置计时器,所以我尝试将消息发送到初始组件,但仅在第一次发送时重置了计时器。
turn-timer.component.ts:
@Component({
selector: 'app-turn-timer',
templateUrl: './turn-timer.component.html',
styleUrls: ['../../../../angry_styles.css']
})
export class TurnTimerComponent implements OnInit
{
public counter : number = 60;
interval = 1000;
public current_player: string;
constructor (private ll: LL, private client: ClientService, private players: PlayersInfo)
{
this.client.messages.subscribe(msg =>
{
switch (msg.SUBJECT)
{
case 'TT_UPDATE':
{
this.counter = msg.COUNTER;
this.current_player = msg.PLAYER_ON_TURN;
}
break;
default:
break;
}
});
}
ngOnInit(): void {}
}
有html:
<ng-container [counter]="counter" [interval]="interval" (value)="value = $event">
<span>{{ value }}</span>
</ng-container>
答案的原始作者有
<input type="number" [(ngModel)]="counter"/>
在他的html中以及每次的时间值
<input>
已更改,倒数计时器将重置为该值。但是,在我的应用中,应该由发送Websocket消息的C#服务器将其重置。
那么我期望得到什么结果:在每条“ TT_UPDATE”消息上,我希望HTML中的{{value}}更改为msg.COUNTER的值。然后,this.counter $ .pipe递减{{value}}。很好只是重置部分不起作用。
顺便说一句。每个消息都已成功接收,我检查了字段名称。这是消息的定义:
export interface Message {
SUBJECT: string;
COUNTER?: number; // This is the problematic field.
PLAYER_ON_TURN?: string;
}
@Injectable()
export class ClientService
{
public messages: Subject < Message > ;
constructor(wsService: WebsocketService) {
this.messages = < Subject < Message >> wsService
.connect(CHAT_URL).pipe(
map((response: MessageEvent): Message => {
console.log(response);
const data = JSON.parse(response.data);
return data;
}), share());
}
我从代码中删除了导入和路径,因此它虽然较短,但它们是正确的。另外,在浏览器控制台中也没有发现错误。
答案 0 :(得分:0)
最后,我自己找到了解决方案。我什至不需要this.counter。我修改了收到消息后的情况:
this.client.messages.subscribe(msg =>
{
switch (msg.SUBJECT)
{
case 'TT_UPDATE':
{
this.ResetTimer(msg.COUNTER); // THIS IS NEW !!!
}
break;
default:
break;
}
});
}
然后我创建了一个新方法,该方法将倒数计时器重置为从消息中收到的值:
ResetTimer(updatedValue: number)
{
this.counter$.next({ count: updatedValue, interval: this.interval });
}
由于我不更改时间间隔,因此我将其设置为相同。有时我想知道事情如何轻松。