求基于TypeScript的Angular 5+Spring Boot WebSocket客户端基础示例
Angular 5 TypeScript WebSocket Client Example
Got it, let's put together a clean, reusable TypeScript-based WebSocket client for Angular 5 that handles connection setup, message sending, and message reception properly.
Step 1: Create a WebSocket Service
First, we'll build a dedicated service to wrap all WebSocket logic—this keeps your components focused on UI and makes the WebSocket functionality reusable across your app.
import { Injectable, OnDestroy } from '@angular/core'; import { Observable, Subject } from 'rxjs'; @Injectable() export class WebSocketService implements OnDestroy { private socket: WebSocket; private messageSubject = new Subject<any>(); constructor() { // Replace this with your actual WebSocket endpoint (e.g., ws://localhost:8080/ws) this.socket = new WebSocket('ws://your-websocket-server-url'); // Handle successful connection this.socket.onopen = () => { console.log('WebSocket connection established successfully'); }; // Process incoming messages from the server this.socket.onmessage = (event) => { try { // Parse JSON messages (adjust if your server sends plain text) const parsedMessage = JSON.parse(event.data); this.messageSubject.next(parsedMessage); } catch (err) { // Fallback for non-JSON messages this.messageSubject.next(event.data); } }; // Handle connection errors this.socket.onerror = (error) => { console.error('WebSocket connection error:', error); this.messageSubject.error(error); }; // Handle connection closure this.socket.onclose = (event) => { console.log('WebSocket connection closed:', event.code, event.reason); this.messageSubject.complete(); }; } // Expose incoming messages as an observable for components to subscribe to getMessages(): Observable<any> { return this.messageSubject.asObservable(); } // Send a message to the WebSocket server sendMessage(message: any): void { if (this.socket.readyState === WebSocket.OPEN) { // Stringify objects, send as-is if it's already a string const payload = typeof message === 'string' ? message : JSON.stringify(message); this.socket.send(payload); } else { console.warn('Cannot send message: WebSocket connection is not open'); } } // Clean up resources when the service is destroyed ngOnDestroy(): void { if (this.socket) { this.socket.close(); } } }
Step 2: Register the Service in Your Module
Add the service to your Angular module's providers array so it can be injected into components:
import { NgModule } from '@angular/core'; import { WebSocketService } from './web-socket.service'; @NgModule({ // ... other module imports/declarations providers: [WebSocketService] }) export class AppModule { }
Step 3: Use the Service in a Component
Here's an example component that uses the service to send messages and display incoming ones:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { WebSocketService } from './web-socket.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-websocket-demo', template: ` <div class="ws-demo"> <h3>Incoming Messages</h3> <ul> <li *ngFor="let msg of receivedMessages">{{ msg }}</li> </ul> <input type="text" [(ngModel)]="newMessage" placeholder="Type a message to send" > <button (click)="sendNewMessage()" [disabled]="!newMessage.trim()">Send</button> </div> ` }) export class WebSocketDemoComponent implements OnInit, OnDestroy { receivedMessages: any[] = []; newMessage: string = ''; private messageSubscription: Subscription; constructor(private webSocketService: WebSocketService) { } ngOnInit(): void { // Subscribe to incoming messages from the service this.messageSubscription = this.webSocketService.getMessages().subscribe({ next: (msg) => { this.receivedMessages.push(msg); }, error: (err) => { console.error('Failed to receive message:', err); }, complete: () => { console.log('Message stream has ended'); } }); } sendNewMessage(): void { this.webSocketService.sendMessage(this.newMessage); this.newMessage = ''; } // Clean up subscription to avoid memory leaks ngOnDestroy(): void { if (this.messageSubscription) { this.messageSubscription.unsubscribe(); } } }
Key Things to Note
- Endpoint Replacement: Swap
ws://your-websocket-server-urlwith your actual server's WebSocket endpoint (e.g.,ws://localhost:8080/chat). - Message Format: The service defaults to parsing JSON messages, but you can remove the try/catch block if your server sends only plain text.
- Connection Checks: The
sendMessagemethod verifies the socket is open before sending—for production, you might add reconnection logic if the connection drops. - Memory Management: Always unsubscribe from observables and close the socket when components/services are destroyed to prevent memory leaks.
内容的提问来源于stack exchange,提问作者d-man
相关产品推荐
相关产品推荐

