【问题标题】:How to connect my component to my socket.io server?如何将我的组件连接到我的 socket.io 服务器?
【发布时间】:2019-09-26 10:15:03
【问题描述】:

我正在尝试让 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】:

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

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

    【讨论】:

    • 非常感谢!我确实忘记在我的 io.emit() 中命名“blueTeam”事件,只是修复了它,一切正常!
    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多