【问题标题】:Unable to reconnect to socket after timeout超时后无法重新连接到套接字
【发布时间】:2020-01-30 10:56:13
【问题描述】:

我在我的 Angular 应用中将此代码作为服务:

import * as io from 'socket.io-client';
import { Observable } from 'rxjs'

export class AppChatService {
    private url = 'http://localhost:3000';
    private socket;    



    constructor() {

        this.socket = io.connect( this.url);

    this.socket.on('connect', function(){
    console.log('connection established');


   });

    this.socket.on('disconnect', function(){
        console.log('reached on disconnect function');
        this.socket.socket.connect();
    }); 



  }



    public disconnectManually(){
        this.socket.disconnect();
        console.log('disconnected manually');
    }


    public sendMessage(message) {
        this.socket.emit('new-message', message);
    }
    public connectToChatroom(roomObject){

        this.socket.emit('create',roomObject);
    }

    public getMessages = () => {
        return Observable.create((observer) => {
            this.socket.on('new-message', (message) => {
                console.log('reached get messages observable app chat service');

                observer.next(message);
            });


        });
    }

}

当我尝试手动断开连接时,“断开连接”功能被成功调用,并且我可以在控制台中看到“已达到断开连接功能”,如预期的那样。但是这个声明: this.socket.socket.connect();

在浏览器中触发此错误:

ERROR TypeError: Cannot read property 'socket' of undefined

我无法理解为什么。任何帮助都将不胜感激。

【问题讨论】:

    标签: angular websocket socket.io frontend


    【解决方案1】:

    那是因为您使用了function 关键字,这会改变this 上下文,请改用箭头函数:

    this.socket.on('disconnect', () => {
        console.log('reached on disconnect function');
        this.socket.connect();
    }); 
    

    您还可以查看 socket.io 中的 Manager 选项,使其自动重新连接

    【讨论】:

    • 试过了,我现在收到这个错误:无法读取未定义的属性“连接”
    • @BlackJack 你确定不只是this.socket.connect()?好像有点奇怪,socket.socket
    猜你喜欢
    • 2015-11-14
    • 2014-12-12
    • 1970-01-01
    • 2012-03-01
    • 2016-06-18
    • 2010-09-05
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多