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)

KeyTypeDescription
baseUrlstringBase Socket.IO server URL
pathstringCustom socket path (e.g., /ws or /socket.io)
transportsstring[]Allowed transports (usually ["websocket"])
autoConnectbooleanWhether to connect automatically after creation
reconnectionbooleanEnable automatic reconnection
reconnectionAttemptsnumberHow many times to retry connection
reconnectionDelaynumberDelay between retries (ms)
auth.tokenstringBearer token sent as Authorization header

⚠️ Validation

All fields above are required.
If any field is missing, init(config) will throw: