socket
Framework: angular
WebSocketService Documentation
π₯ Importing the Service
ts
import { WebSocketService } from "universe-code/socket";
Initialize once (e.g., in App.ts)
π app.ts
ts
constructor() {
WebSocketService.instance.init({
baseUrl: "https://example.com",
path: "/ws",
transports: ["websocket"],
autoConnect: true,
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
auth:{
token: "USER_AUTH_TOKEN",
}
});
}
Note:
if autoConnect is false then connect manually through this function
ts
WebSocketService.instance.connect();
π Update Token (login / logout)
ts
WebSocketService.instance.setToken(/*your token*/);
π© Subscribe to market
ts
WebSocketService.instance.subscribeMarket(/*Your market id array here*/); //e.g [1,2,3,4,5]
ποΈ Unsubscribe
ts
WebSocketService.instance.unsubscribeMarket(/*Your market id array here*/); //e.g [1,2,3,4,5]
π Listen to event in React component
ts
//onEvent( your event name, callback function )
ngOnInit() {
const off = WebSocketService.instance.onEvent("marketUpdate", (data: any) => {
console.log("market =>", data);
});
// unsubscribe on destroy
this.offListener = off;
}
π€ Emit custom event
ts
// sendMessage( your evenrt name, your message)
WebSocketService.instance.sendMessage("customEvent", { hello: "world" });
β Dissconnect Socket
ts
WebSocketService.instance.disconnect();
π¦ Config Object (Required Fields)
| Key | Type | Description |
|---|---|---|
baseUrl | string | Base Socket.IO server URL |
path | string | Custom socket path (e.g., /ws or /socket.io) |
transports | string[] | Allowed transports (usually ["websocket"]) |
autoConnect | boolean | Whether to connect automatically after creation |
reconnection | boolean | Enable automatic reconnection |
reconnectionAttempts | number | How many times to retry connection |
reconnectionDelay | number | Delay between retries (ms) |
auth.token | string | Bearer token sent as Authorization header |
β οΈ Validation
All fields above are required.
If any field is missing, init(config) will throw: