Instant Messaging Chat App
Build a chat application UI in Angular that connects to a WebSocket server to send and receive messages in real-time.
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
private chatWebSocket: WebSocketSubject<any>;
public connect(url: string): void {
if (!this.chatWebSocket || this.chatWebSocket.closed) {
this.chatWebSocket = webSocket(url);
}
}
public sendMessage(message: any): void {
this.chatWebSocket.next(message);
}
public getMessages(): Observable<any> {
return this.chatWebSocket.asObservable();
}
public close(): void {
this.chatWebSocket.complete();
}
}
This code provides a WebsocketService service that handles the WebSocket connection including connecting, sending, and receiving messages through observables. It's using rxjs WebSocketSubject for simplified websocket usage.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebsocketService } from './websocket.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit, OnDestroy {
message = '';
messages: string[] = [];
private subscription: Subscription;
constructor(private websocketService: WebsocketService) { }
ngOnInit(): void {
this.websocketService.connect('wss://yourwebsocketserver.com');
this.subscription = this.websocketService.getMessages().subscribe((message: string) => {
this.messages.push(message);
});
}
sendMessage(): void {
this.websocketService.sendMessage(this.message);
this.message = '';
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
this.websocketService.close();
}
}
This code provides a ChatComponent that initializes a WebSocket connection and handles sending and receiving chat messages. It subscribes to the messages observable from WebsocketService to update the chat in real-time and cleans up on destroy.