Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply.
The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then calling that service from the component instead.
Here is the existing code snippet residing in the component:
import { Component } from '@angular/core';
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
myWebSocket: WebSocketSubject<any> = webSocket('ws://localhost:8888');
constructor() {
this.myWebSocket.subscribe(
msg => console.log('message received: ' + msg),
err => console.log(err),
() => console.log('complete')
);
}
sendMessageToServer(msg) {
const dte = Date.now();
this.myWebSocket.next({message: `${msg} - ${dte}` });
}
}
In addition to this, I have created a new service as follows:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class WsService {
constructor() { }
}
Now the question arises, how should I transition from having the code in the component to utilizing the service? For instance, should the subscription logic be moved to the service or kept in the component?