如何将组件连接到我的socket.io服务器?

问题描述 投票:0回答:1

我正在尝试使socket.io服务器在两个组件之间进行通信:一个用于发送数据的命令界面,以及一个仅接收数据的覆盖层。

这是我的代码

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

}

最后是我的服务器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}`);
});

我的服务器收到了blueTeamName,但是我不确定它是否会发出它,因为我的overlay.component.ts从未收到它。我想知道我在做什么错

angular typescript socket.io
1个回答
0
投票

我对给定的来源做了一些修改。

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在这里,您在发出部分错误。

socket.on('blueTeam', (name) => {
  io.emit('blueTeam',name);
});
© www.soinside.com 2019 - 2024. All rights reserved.