Angular 6中如何在Socket响应成功时调用passDataToService()函数
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:
1. Use an Arrow Function (Recommended)
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

