【发布时间】:2021-04-07 21:06:38
【问题描述】:
在我的示例应用程序中,我将 Web 客户端连接到 socket.io 服务器,这部分工作正常。服务器(通过 websocket)发送的数据被客户端正确接收,但是......当变量改变时,它们不会反映在 UI 中:
这是我的基本代码:
import { Component } from '@angular/core';
import io from 'socket.io-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private socket: any;
public total: number = 0;
constructor() {
this.socket = io('');
// Update scores when a new vote is received
this.socket.on('scores', function (json) {
// Extract number of votes for each item (a / b)
let data = JSON.parse(json);
let a = parseInt(data["a"] || 0);
let b = parseInt(data["b"] || 0);
// Setting this prop to indicate the total number of votes
this.total = a + b; // <== this is not updated in the html vue
...
});
}
}
在 html 中,我只是有类似的东西:
<div id="result">
<span *ngIf="total == 0">No votes yet</span>
<span *ngIf="total == 1">{{total}} vote</span>
<span *ngIf="total >= 2">{{total}} votes</span>
</div>
任何提示我错过了什么?
【问题讨论】: