1. Install Required Dependencies
Install the socket.io-client
package:
npm install socket.io-client
2. Create a WebSocket Service
Create a service to handle WebSocket communication.
import { Injectable } from '@angular/core';
import { io, Socket } from 'socket.io-client';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class WebSocketService {
private socket: Socket;
constructor() {
this.socket = io('http://localhost:3000'); // Replace with your backend URL
}
// Emit an event to the server
sendNotification(message: string) {
this.socket.emit('sendNotification', { message });
}
// Listen for an event from the server
onNotification(): Observable<{ message: string }> {
return new Observable((observer) => {
this.socket.on('receiveNotification', (data) => {
observer.next(data);
});
return () => {
this.socket.off('receiveNotification');
};
});
}
}
3. Use the Service in a Component
Inject the service into a component to send and receive notifications.
import { Component, OnInit } from '@angular/core';
import { WebSocketService } from './web-socket.service';
@Component({
selector: 'app-notifications',
template: `
<div>
<h2>Real-Time Notifications</h2>
<button (click)="sendNotification()">Send Notification</button>
<ul>
<li *ngFor="let notification of notifications">
{{ notification.message }}
</li>
</ul>
</div>
`,
})
export class NotificationsComponent implements OnInit {
notifications: { message: string }[] = [];
constructor(private webSocketService: WebSocketService) {}
ngOnInit() {
this.webSocketService.onNotification().subscribe((notification) => {
this.notifications.push(notification);
});
}
sendNotification() {
this.webSocketService.sendNotification('Hello from Angular!');
}
}
Run the Application
- Start the Angular application:
ng serve
Leave a Reply