Nakkarst
Nakkarst

Reputation: 47

How to connect my component to my socket.io server?

I'm trying to make a socket.io server communicate between two components: a command interface to send data, and an overlay which just receives it.

Here is my code

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);
    })
  }

}

And finally my server 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(`started on port: ${port}`);
});

My server receives blueTeamName, but I'm not sure if it emits it, as my overlay.component.ts never gets it. I would like to know what am I doing wrong

Upvotes: 0

Views: 105

Answers (1)

Beller
Beller

Reputation: 888

I have made a few modification on the given source.

app.module.ts

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...
imports: [
  ..., FormsModule, ReactiveFormsModule, ...
],
...

interface.component.html :

<form [formGroup]="interfaceForm">
    <input type="text" formControlName="message" >
    <button (click)="sendBlueTeam()">Submit</button>
</form>

interface.component.ts :

import { Component, OnInit} from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { DataService } from '../../services/data.service';

@Component({
  selector: 'app-interface',
  templateUrl: './interface.component.html',
  styleUrls: ['./interface.component.sass']
})
export class InterfaceComponent implements OnInit {

interfaceForm: FormGroup;
constructor(public dataService: DataService) { }

  ngOnInit() {
    this.interfaceForm = new FormGroup({
      'message': new FormControl(null, [Validators.required, Validators.min(1)])
    });
  }

  sendBlueTeam() {
    this.dataService.sendBlueTeam(this.interfaceForm.value.message);
    this.interfaceForm.reset();
  }
}

data.service.ts :

this.socket = io('ws://localhost:3000', {transports: ['websocket']});

overlay.component.ts :

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';

@Component({
  selector: 'app-overlay',
  templateUrl: './overlay.component.html',
  styleUrls: ['./overlay.component.sass']
})
export class OverlayComponent implements OnInit {
result: string;
constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getBlueTeam()
    .subscribe(data => {
      this.result = data;
      console.log(data);
    });
  }
}

overlay.component.html

<p>{{result}}</p>

index.js Here you have a mistake in emit part.

socket.on('blueTeam', (name) => {
  io.emit('blueTeam',name);
});

Upvotes: 1

Related Questions