I am facing a challenge in setting up a socket.io server to facilitate communication between two components: a command interface for sending data, and an overlay component for receiving it.
Below is the code snippet:
interface.component.html :
<input [(ngModel)]="blueTeamName">
<button (click)="sendBlueTeam()">Submit</button>
interface.component.ts :
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DataService } from '../data.service';
@Component({
selector: 'app-interface',
templateUrl: './interface.component.html',
styleUrls: ['./interface.component.css']
})
export class InterfaceComponent implements OnInit {
public blueTeamName: string;
constructor(public dataService: DataService) { }
ngOnInit() { }
sendBlueTeam() {
this.dataService.sendBlueTeam(this.blueTeamName);
}
}
data.service.ts :
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
public url = 'http://localhost:3000';
public socket;
constructor() {
this.socket = io(this.url);
}
public sendBlueTeam(name) {
this.socket.emit('blueTeam', name);
}
public getBlueTeam = () => {
return Observable.create((observer) => {
this.socket.on('blueTeam', (name) => {
observer.next(name);
});
});
}
overlay.component.ts :
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-overlay',
templateUrl: './overlay.component.html',
styleUrls: ['./overlay.component.css']
})
export class OverlayComponent implements OnInit {
public blueTeamName: string;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getBlueTeam().subscribe((name: string) => {
this.blueTeamName = name;
console.log(name);
})
}
}
Lastly, my server script index.js :
let express = require('express')
let app = express();
let http = require('http');
let server = http.Server(app);
let socketIO = require('socket.io');
let io = socketIO(server);
const port = process.env.PORT || 3000;
io.on('connection', (socket) => {
console.log('user connected');
socket.on('blueTeam', (name) => {
io.emit(name);
});
}
server.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
While my server successfully receives the blueTeamName
, it seems to be failing at emitting it, causing the overlay.component.ts
to not receive anything. I would greatly appreciate any insights into what might be going wrong here.