Angular6 / Socket:套接字调用触发“ console.log()”,但在其他功能中失败

时间:2018-08-23 23:52:22

标签: angular sockets socket.io angular6

在尝试使Socket与Angular 6配合使用时出现问题。套接字可以平稳运行并在console.log上记录从服务器接收的信息,但似乎不想在其上执行任何其他功能。

代码如下:

这是我的服务器的样子(套接字设置在底部):

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 + '/ANGULAR FILE'));

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('CreatedRoom',function(data){      
        //console.log("Socket id is",socket.id)
        context = {
            room:data['room']['room']['name']
        }
        socket.broadcast.emit('newRoomAlert',context)

    })

});

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

我正在使用名为myRooms的组件中的套接字。这是myrooms.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,
    private toaster: ToasterService) {
      this.socket = io.connect('http://localhost:1337');
     }

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

    this.socket.on('newRoomAlert',function(data){
      this.getJoinedRooms();
    })

  }

  getAllRooms() {
    //this gets all the rooms created by the user
  }

  getJoinedRooms() {
   //this gets all the rooms the user has joined
  }

  createRoom() {
    this.new_room['email'] = this.user_email;
    let observable = this._httpService.createRoom(this.new_room);
    observable.subscribe(data=>{
      if (data['status'] == 500) {
        this.errors = data['errors']['errors']
        console.log(this.errors)
      }
      else {
        console.log(data)
        this.socket.emit('CreatedRoom',{room:data})
           //This socket emit works perfectly
        this.new_room = {name:""};
        this.getAllRooms();
        this.toaster.Success("You've created a new room!")
      }
    })
  }

}

我的主要问题是以下代码:

this.socket.on('newRoomAlert',function(data){
          this.getJoinedRooms();
        })

套接字由于某种原因无法识别该功能。有人可以帮忙吗?当我在套接字中仅放入“ console.log(data)”时,它确实起作用。它确实将信息记录在我的控制台上。

这是我在Chrome控制台上看到的错误:

ERROR TypeError: this.getJoinedRooms is not a function
    at Socket.<anonymous> (my-rooms.component.ts:47)
    at Socket.push../node_modules/component-emitter/index.js.Emitter.emit (index.js:133)
    at Socket.push../node_modules/socket.io-client/lib/socket.js.Socket.onevent (socket.js:270)
    at Socket.push../node_modules/socket.io-client/lib/socket.js.Socket.onpacket (socket.js:228)
    at Manager.<anonymous> (index.js:21)
    at Manager.push../node_modules/component-emitter/index.js.Emitter.emit (index.js:133)
    at Manager.push../node_modules/socket.io-client/lib/manager.js.Manager.ondecoded (manager.js:332)
    at Decoder.<anonymous> (index.js:21)
    at Decoder.push../node_modules/socket.io-parser/node_modules/component-emitter/index.js.Emitter.emit (index.js:134)
    at Decoder.push../node_modules/socket.io-parser/index.js.Decoder.add (index.js:246)

0 个答案:

没有答案