Angular 6 和 Socket.IO - Socket.On 不工作

Posted

技术标签:

【中文标题】Angular 6 和 Socket.IO - Socket.On 不工作【英文标题】:Angular 6 and Socket.IO - Socket.On not working 【发布时间】:2019-01-29 07:13:36 【问题描述】:

我正在尝试将 socket.io 与 Angular 6 项目一起使用,但它似乎无法正常工作。这是我的问题:

我已经安装了 socket.io-client(带有 npm)

这是我的服务器代码:

var express = require('express');

var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json());

var path = require('path');

app.use(express.static(__dirname + '/client/public/dist/public'));

var db_url = 'mongodb://localhost:27017/DBName'

require('./server/config/mongoose.js')(db_url);

require('./server/config/routes.js')(app)

app.all("*", (req,res,next) => 
    res.sendFile(path.resolve("./client/public/dist/public/index.html"))
  );

const server = app.listen(1337);
console.log("listening on port 1337")

const io = require('socket.io')(server);

io.on('connection', function (socket) 

    socket.on('init',function()      
        console.log("Socket id is",socket.id)
        io.emit('message',msg:'testing socket')
        console.log("after emit statement")
    )

);

app.listen(8000, function() 
    console.log("listening on port 8000");
)

在我的 Angular 项目中,我位于组件的 ts 文件 (my-rooms.component.ts) 中,代码如下:

import  Component, OnInit  from '@angular/core';
import  HttpService  from '../http.service';
import  ActivatedRoute, Params, Router  from '@angular/router';
import  Injectable  from '@angular/core';
import * as io from 'socket.io-client';

@Component(
  selector: 'app-my-rooms',
  templateUrl: './my-rooms.component.html',
  styleUrls: ['./my-rooms.component.css']
)

export class MyRoomsComponent implements OnInit 
  user_email = localStorage.getItem('email');
  new_room = name:"";
  errors = ;
  all_rooms = [];
  joined_rooms = [];
  socket: SocketIOClient.Socket;

  constructor(private _httpService: HttpService,
    private _route: ActivatedRoute,
    private _router: Router) 
      this.socket = io.connect();
     

  ngOnInit() 
    console.log(localStorage)
    if (!localStorage.getItem('loggedIn')) 
      this._router.navigate(['/home']);
    
    else 
      this.getAllRooms();
      this.getJoinedRooms();
    

    this.socket.emit('init');
    this.socket.on('message',function(data)
      console.log(data.msg)
    ) 
  

//Plus other functions for this component

基本上,在终端或浏览器的控制台中都没有记录任何内容。有人能帮忙吗?谢谢!

【问题讨论】:

【参考方案1】:

你应该听 Node.js 端口

constructor(
    private _httpService: HttpService,
    private _route: ActivatedRoute,
    private _router: Router
) 
    this.socket = io('http://localhost:1337');

【讨论】:

创建服务并在所有组件之间共享数据

以上是关于Angular 6 和 Socket.IO - Socket.On 不工作的主要内容,如果未能解决你的问题,请参考以下文章

服务器重新启动socket.io socketio-jwt后Angular 6验证客户端

Angular2 CLI Socket.io(第三方库导入)

在 angular-cli@webpack 中使用 socket.io-client

如何使用 Angular 和 Jasmine 模拟 socket.io

angular 4/socket.io 访问全局变量和函数调用

让 angular-socket-io 与 Grunt 一起工作