【问题标题】:Cannot have UI updated when data received through socket.io in Angular通过 Angular 中的 socket.io 接收数据时无法更新 UI
【发布时间】: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>

任何提示我错过了什么?

【问题讨论】:

    标签: angular socket.io


    【解决方案1】:

    遗憾的是,this.total 不是组件的属性,因为它在函数范围内。相反,您应该使用箭头函数来纠正这一点:

    this.socket.on('scores',  (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 should be updated in the HTML now
          ...
        });
    

    【讨论】:

    • 哇!!非常感谢,你拯救了我的夜晚:)
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多