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.
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.
A serializer used to create messages from passed values before the
messages are sent to the server. Defaults to JSON.stringify.
deserializer
A deserializer used for messages arriving on the socket from the
server. Defaults to JSON.parse.
openObserver
An Observer that watches when open events occur on the underlying web socket.
closeObserver
An Observer than watches when close events occur on the underlying webSocket
closingObserver
An Observer that watches when a close is about to occur due to
unsubscription.
WebSocketCtor
A WebSocket constructor to use. This is useful for situations like using a
WebSocket impl in Node (WebSocket is a DOM API), or for mocking a WebSocket
for testing purposes
binaryType
Sets the binaryType property of the underlying WebSocket.