You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 6中如何在Socket响应成功时调用passDataToService()函数

Fixing the this Context Issue in WebSocket onmessage Handler

Hey there! I can spot exactly what's going wrong here. When you use a regular function for ws.onmessage, the this inside that function refers to the WebSocket instance itself, not your Angular component. That's why this.passDataToService isn't working—it can't find the method on the WebSocket object.

Here are three straightforward fixes to get your component's this context into that handler:

Arrow functions inherit the this context from their surrounding scope (your component in this case). This is the cleanest approach in modern TypeScript:

mySocketFun() {
  if ('WebSocket' in window) {
    const ws = new WebSocket('ws://localhost:2012/echo');
    ws.onopen = () => {
      // Note: WebSocket.send only accepts ONE parameter—pack your data into a string!
      ws.send(JSON.stringify(["4001", "billNo12", 1000]));
    };
    ws.onmessage = (evt) => {
      this.passDataToService(evt);
    };
  }
}

2. Save the Component's this to a Variable

If you prefer not to use arrow functions, you can store your component's this in a variable (like self or componentThis) before defining the handler:

mySocketFun() {
  if ('WebSocket' in window) {
    const self = this; // Save component's this reference
    const ws = new WebSocket('ws://localhost:2012/echo');
    ws.onopen = function() {
      ws.send(JSON.stringify(["4001", "billNo12", 1000]));
    };
    ws.onmessage = function(evt) {
      self.passDataToService(evt); // Use the saved reference instead of `this`
    };
  }
}

3. Bind this to the Handler Function

You can explicitly bind your component's this to the handler function using bind():

mySocketFun() {
  if ('WebSocket' in window) {
    const ws = new WebSocket('ws://localhost:2012/echo');
    ws.onopen = function() {
      ws.send(JSON.stringify(["4001", "billNo12", 1000]));
    };
    ws.onmessage = function(evt) {
      this.passDataToService(evt);
    }.bind(this); // Bind component's `this` to the function
  }
}

Quick Side Note

I noticed you're passing three arguments to ws.send()—but the WebSocket send() method only accepts a single parameter (a string, Blob, or ArrayBuffer). To send multiple values, you'll need to serialize them into a string (like using JSON.stringify as shown above) so your backend can parse them correctly.

内容的提问来源于stack exchange,提问作者Lavkush Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:57:48