This is simple WebSocket client for Angular. simple-ng-websocket is thin wrapper at Browser's WebSocket.
To install simple-ng-websocket in the current directory, run:
npm install simple-ng-websocket
simple-ng-websocket can be use to Angular provider.
First, you must define it in the providers.
import { NgModule } from '@angular/core';
import { SimpleNgWebSocket, CONNECT_URL, LOGGER } from 'simple-ng-websocket';
@NgModule({
providers: [
{ provide: CONNECT_URL, useValue: 'ws://' + window.location.host + '/ws/' },
{ provide: LOGGER, useValue: (level, message) => console.log(message) },
SimpleNgWebSocket,
],
})
export class AppModule { }
You can inject CONNECT_URL
and LOGGER
parameters.
CONNECT_URL
: The URL to which to connect. IfCONNECT_URL
is not specified, the client connect to'ws://' + window.location.host + '/'
or'wss://' + window.location.host + '/'
.LOGGER
: The logger for this client's log event such as OPEN, CLOSE, SEND, RECEIVE and ERROR.
Then, you can use it on your logic code.
import { Injectable } from '@angular/core';
import { SimpleNgWebSocket } from 'simple-ng-websocket';
@Injectable()
export class SampleService {
constructor(private ngws: SimpleNgWebSocket) {
this.ngws.on('message', (msg) => {
console.log(msg);
});
}
sendMessage(msg: string): void {
this.ngws.send(msg);
}
}
url
{String} It is the same asCONNECT_URL
.logger
{Function} It is the same asLOGGER
.
Create a new websocket connection. The constructor call connect()
automatically.
ev
{Event}ngws
{SimpleNgWebSocket}
Emitted when the handshake is complete. ev
is through from Browser's WebSocket
.
ev
{MessageEvent}ngws
{SimpleNgWebSocket}
Emitted when a message is received from the server. ev
is through from Browser's WebSocket
.
ev
{CloseEvent}ngws
{SimpleNgWebSocket}
Emitted when the connection is closed. ev
is through from Browser's WebSocket
.
ev
{ErrorEvent}ngws
{SimpleNgWebSocket}
Emitted when an error occurs. ev
is through from Browser's WebSocket
.
Open a new websocket connection.
code
{Number} A numeric value indicating the status code explaining why the connection is being closed.reason
{String} A human-readable string explaining why the connection is closing.
Close the websocket connection.
message
{String} The data to send to the server.toJson
{Boolean} Specifies whether message should beJSON.stringify()
or not. Defaults to true.
Sends message
through the connection. If the connection was not opend, send()
call connect()
automatically.
- {String}
The URL of the WebSocket server.
- {WebSocket}
The connection instance of the raw WebSocket
.
You can find a example web application here.