I need assistance with a component that performs two tasks...
- Establishes a connection to the server via websocket
- Sends a message and displays the response.
The current implementation is functional, and here is the code snippet for the component:
app.component.ts
import { Component } from '@angular/core';
import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject';
export class Message {
constructor(
public sender: string,
public content: string,
public isBroadcast = false,
) { }
}
@Component({
selector: 'app-terminal',
templateUrl: './terminal.component.html',
styleUrls: ['./terminal.component.scss']
})
export class TerminalComponent {
public serverMessages = new Array<Message>();
public clientMessage = '';
public isBroadcast = false;
public sender = 'client';
private socket$: WebSocketSubject<Message>;
server1 = 'ws://localhost:8999';
constructor() {}
public send() {
const message = new Message(this.sender, this.clientMessage, this.isBroadcast);
this.serverMessages.push(message);
this.socket$.next(message);
this.clientMessage = '';
}
connectToServer(serverUrl) {
this.serverMessages = [];
this.clientMessage = '';
this.socket$ = new WebSocketSubject(serverUrl);
this.socket$.subscribe(
(message) => this.serverMessages.push(message),
(err) => console.error(err),
() => console.warn('Completed!')
);
}
}
While both methods - connectToServer() and send() - are operational, I seek to consolidate them into a service for reusability across various components without duplication of code.
Hence, I've introduced the service:
This is my progress so far:
import { Injectable } from '@angular/core';
import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject';
export class Message {
constructor(
public sender: string,
public content: string,
public isBroadcast = false,
) { }
}
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
public serverMessages = new Array<Message>();
public clientMessage = '';
public isBroadcast = false;
public sender = 'client';
private socket$: WebSocketSubject<Message>;
server1 = 'ws://localhost:8999';
constructor() {}
connect(serverUrl) {
// Implementation pending
}
send(message) {
// Implementation pending
}
}
My query pertains to incorporating these methods in the service so they can be easily invoked from the component.