WebSockets with Angular
WebSockets provide a way to open a persistent connection between the client and server, allowing real-time communication. This guide covers the basics of setting up and using WebSockets with Angular.
Setting Up WebSocket Service
Create a WebSocket service to manage the connection and handle messages:
// src/app/websocket.service.ts
import { Injectable } from '@angular/core';
import { Observable, Observer } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
private socket: WebSocket;
connect(url: string): Observable {
this.socket = new WebSocket(url);
return new Observable((observer: Observer) => {
this.socket.onmessage = (event) => observer.next(event.data);
this.socket.onerror = (event) => observer.error(event);
this.socket.onclose = () => observer.complete();
return () => this.socket.close();
});
}
sendMessage(message: any) {
this.socket.send(JSON.stringify(message));
}
}
Using WebSocket Service in a Component
Use the WebSocket service in a component to connect to the server and handle messages:
// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { WebSocketService } from './websocket.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
messages: string[] = [];
message: string = '';
constructor(private webSocketService: WebSocketService) {}
ngOnInit() {
this.webSocketService.connect('ws://your-websocket-url').subscribe(
(message) => this.messages.push(message),
(error) => console.error('WebSocket error:', error),
() => console.warn('WebSocket connection closed')
);
}
sendMessage() {
this.webSocketService.sendMessage(this.message);
this.message = '';
}
}
Template for WebSocket Component
Create a template to display and send messages:
// src/app/app.component.html
WebSocket Chat
Error Handling
Handle errors gracefully in your WebSocket service:
// src/app/websocket.service.ts
connect(url: string): Observable {
this.socket = new WebSocket(url);
return new Observable((observer: Observer) => {
this.socket.onopen = () => console.log('WebSocket connection opened');
this.socket.onmessage = (event) => observer.next(event.data);
this.socket.onerror = (event) => observer.error('WebSocket error:', event);
this.socket.onclose = () => observer.complete();
return () => this.socket.close();
});
}
Reconnecting WebSocket
Implement reconnection logic to handle WebSocket disconnections:
// src/app/websocket.service.ts
import { Injectable } from '@angular/core';
import { Observable, Observer, timer } from 'rxjs';
import { switchMap, retryWhen, delayWhen } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
private socket: WebSocket;
connect(url: string): Observable {
return timer(0, 5000).pipe(
switchMap(() => this.createWebSocket(url)),
retryWhen(errors => errors.pipe(delayWhen(() => timer(5000))))
);
}
private createWebSocket(url: string): Observable {
this.socket = new WebSocket(url);
return new Observable((observer: Observer) => {
this.socket.onmessage = (event) => observer.next(event.data);
this.socket.onerror = (event) => observer.error(event);
this.socket.onclose = () => observer.complete();
return () => this.socket.close();
});
}
sendMessage(message: any) {
this.socket.send(JSON.stringify(message));
}
}
Key Points
- Create a WebSocket service to manage the connection and handle messages.
- Use the WebSocket service in a component to connect to the server and handle messages.
- Create a template to display and send messages using Angular's data binding.
- Handle errors gracefully in your WebSocket service.
- Implement reconnection logic to handle WebSocket disconnections.
Conclusion
Using WebSockets with Angular allows you to implement real-time communication features in your applications. By creating a WebSocket service, using it in your components, handling errors, and implementing reconnection logic, you can create robust and responsive real-time applications. Happy coding!