Reputation: 137
I have a script that connects to server using WebSocket
export class AppComponent {
connection_status = false;
message = '';
public connect() {
this.socket = io('http://localhost:5001');
this.socket.on('connected', this.connection_established);
}
}
I would like to change the connection_status
variable when connected
message is received and save the content of the message to message
variable.
Upvotes: 1
Views: 74
Reputation: 6341
Instead of extra binding simply use the arrow function, which has a lexical scoping to this
context (means this
will be preserved and accessible inside the arrow function body).
Also: it seems you're not using not WebSocket, but rather Socket.IO, which is built on top of WebSocket. According to the official Socket.IO API documentation you should use socket.on("connect"
instead of socket.on("connected"
.
Also you gave the same name to the boolean flag "connection_established" and to the method, which sets it to true. This would error out: Duplicate identifier 'connection_established'.ts(2300)
Also: it would be good idea to register event handlers before trying to connect (imagine connection is already done by the time you haven't yet register your socket.on()
handler and only few milliseconds later you register it, but alas - a bit too late.
Here's how to "Do It The Right Way" (or in this case you could simply inline setting boolean flag inside arrow f-n instead of extra call for 2 code lines):
export class AppComponent {
connection_status = false
message = ''
public connect() {
socket.on('connect', () => this.set_connection_established())
this.socket = io('http://localhost:5001')
}
set_connection_established() {
this.connection_established = true
this.message = 'connected'
}
}
:)
Upvotes: 0
Reputation: 731
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';
}
}
Upvotes: 1