【问题标题】:How to act on callback function如何作用于回调函数
【发布时间】:2017-07-25 12:07:33
【问题描述】:

我有一个使用 WebSocket 连接到服务器的脚本

export class AppComponent {

  connection_status = false;
  message = '';

  public connect() {
    this.socket = io('http://localhost:5001');
    this.socket.on('connected', this.connection_established);
  }
}

我想在收到connected 消息时更改connection_status 变量并将消息内容保存到message 变量。

【问题讨论】:

    标签: angular socket.io


    【解决方案1】:
    export class AppComponent {
    
      connection_status = false;
      message = '';
    
      public connect() {
        this.socket = io('http://localhost:5001');
        this.socket.on('connected', this.connection_established.bind(this));
      }
    
      connection_established() {
        this.connection_established = true;
        this.message = 'connected';
      }
    }
    

    【讨论】:

    • 不应该是'connect'作为事件名称而不是'connected'吗?而且我认为这将失败,因为thisconnection_established 回调中的上下文错误。
    • 已编辑以在回调中维护 this 的上下文。我不知道事件是连接还是连接;但据我了解,问题是关于如何处理回调
    • 正如@cyrix 所说,它不起作用,因为this 的上下文已经改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多