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

Angular 6 and Socket.IO - Socket.On not working

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

我已经安装了 socket.io-客户端(使用 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

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

你应该听 Node.js 端口

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