简体   繁体   中英

Unable to reconnect to socket after timeout

I have this code as a service in my angular app:

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


        });
    }

}

when i try to disconnect manually, the 'on disconnect' function gets successfully called and i can see 'reached on disconnect function' in console as expected. But this statement : this.socket.socket.connect();

triggers this error in the browser:

ERROR TypeError: Cannot read property 'socket' of undefined

and I'm unable to understand why. Any help at all would be much appreciated.

That's because you are using the function keyword, this changes the this context, use an arrow function instead:

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

You can also look into the Manager option from socket.io, to have it auto reconnect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM