'Connecting a WebSocket in Angular
I have WebSocket Connection in Node which works fine. Now I want to use it in Angular with a rxjs websocket, but I have no idea how to solve the connection.
const WebSocket = require('ws');
const ws = new WebSocket('wss://example.com');
ws.on('open', function open() {
// on connection, send our authentication request
ws.send(JSON.stringify({action: 'auth', key: apiKey, secret: apiSecret}));
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function incoming(data) {
console.log(data)
var msg = JSON.parse(data);
if (msg.type === 'status' && msg.status === 'authenticated') {
// if we got authentication confirmation, send subscribe event to the server
ws.send(JSON.stringify({action: 'subscribe', buckets: ['exampleBucket']}));
}
});
Solution 1:[1]
Listening for messages from the server
import { webSocket } from "rxjs/webSocket";
const subject = webSocket('wss://example.com');
subject.subscribe(
msg => console.log('message received: ' + msg), // Called whenever there is a message from the server.
err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
() => console.log('complete') // Called when connection is closed (for whatever reason).
);
Pushing messages to the server
import { webSocket } from "rxjs/webSocket";
const subject = webSocket('wss://example.com');
subject.subscribe();
// Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
// since no connection was established!
subject.next({message: 'some message'});
// This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!
subject.complete(); // Closes the connection.
subject.error({code: 4000, reason: 'I think our app just broke!'});
// Also closes the connection, but let's the server know that this closing is caused by some error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sayooj V R |