WebSocketSubjectConfig
WebSocketSubjectConfig is a plain Object that allows us to make our webSocket configurable.
interface WebSocketSubjectConfig<T> {
url: string
protocol?: string | Array<string>
resultSelector?: (e: MessageEvent) => T
serializer?: (value: T) => WebSocketMessage
deserializer?: (e: MessageEvent) => T
openObserver?: NextObserver<Event>
closeObserver?: NextObserver<CloseEvent>
closingObserver?: NextObserver<void>
WebSocketCtor?: {...}
binaryType?: 'blob' | 'arraybuffer'
}
Description
Provides flexibility to webSocket
It defines a set of properties to provide custom behavior in specific
moments of the socket's lifecycle. When the connection opens we can
use openObserver
, when the connection is closed closeObserver
, if we
are interested in listening for data comming from server: deserializer
,
which allows us to customize the deserialization strategy of data before passing it
to the socket client. By default deserializer
is going to apply JSON.parse
to each message comming
from the Server.
Example
deserializer, the default for this property is JSON.parse
but since there are just two options
for incomming data, either be text or binarydata. We can apply a custom deserialization strategy
or just simply skip the default behaviour.
import { webSocket } from 'rxjs/webSocket';
const wsSubject = webSocket({
url: 'ws://localhost:8081',
//Apply any transformation of your choice.
deserializer: ({data}) => data
});
wsSubject.subscribe(console.log);
// Let's suppose we have this on the Server: ws.send("This is a msg from the server")
//output
//
// This is a msg from the server
serializer allows us tom apply custom serialization strategy but for the outgoing messages
import { webSocket } from 'rxjs/webSocket';
const wsSubject = webSocket({
url: 'ws://localhost:8081',
//Apply any transformation of your choice.
serializer: msg => JSON.stringify({channel: "webDevelopment", msg: msg})
});
wsSubject.subscribe(() => subject.next("msg to the server"));
// Let's suppose we have this on the Server: ws.send("This is a msg from the server")
//output
//
// {"channel":"webDevelopment","msg":"msg to the server"}
closeObserver allows us to set a custom error when an error raise up.
import { webSocket } from 'rxjs/webSocket';
const wsSubject = webSocket({
url: 'ws://localhost:8081',
closeObserver: {
next(closeEvent) {
const customError = { code: 6666, reason: "Custom evil reason" }
console.log(`code: ${customError.code}, reason: ${customError.reason}`);
}
}
});
//output
// code: 6666, reason: Custom evil reason
openObserver, Let's say we need to make some kind of init task before sending/receiving msgs to the webSocket or sending notification that the connection was successful, this is when openObserver is usefull for.
import { webSocket } from 'rxjs/webSocket';
const wsSubject = webSocket({
url: 'ws://localhost:8081',
openObserver: {
next: () => {
console.log('connetion ok');
}
},
});
//output
// connetion ok`