【问题标题】:Angular 6 and Socket.IO - Socket.On not workingAngular 6 和 Socket.IO - Socket.On 不工作
【发布时间】: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

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

【问题讨论】:

    标签: angular socket.io mean-stack angular6


    【解决方案1】:

    你应该听 Node.js 端口

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

    【讨论】:

    • 创建服务并在所有组件之间共享数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2013-05-12
    • 2018-11-25
    • 2018-12-18
    • 2021-09-26
    • 2016-02-15
    相关资源
    最近更新 更多