超时后无法重新连接到套接字

时间:2020-01-30 10:56:13

标签: angular websocket socket.io frontend

我的角度应用程序中有以下代码作为服务:

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

,我不明白为什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

那是因为您使用的是function关键字,这会更改this的上下文,请改用箭头功能:

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

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