简体   繁体   中英

When socket.io emits to 'login', TypeError: Cannot read property 'navigate' of undefined

I am working on a chat app using angular 4 and socket.io.
Here is my code

export class UserService {
socket;


// determines if a user is logged in or not
loggedIn: '';

constructor(private router: Router) {
    this.socket = io('http://localhost:8890');
    this.socket.on('login', function (result) {
        if (result) {
            this.loggedIn = true;
            this.router.navigate(['/profile']);
        } else {
            this.loggedIn = false;
        }
        localStorage.setItem('loggedIn', this.loggedIn);
        console.log(result);
    });
}}

So whenever socket.io emits to 'login', I get this error on my console

I changed the code and initialised router out of the constructor:

export class UserService {
socket;


// determines if a user is logged in or not
loggedIn: '';
router: Router;

constructor() {
    this.socket = io('http://localhost:8890');
    this.socket.on('login', function (result) {
        if (result) {
            this.loggedIn = true;
            this.router.navigate(['/profile']);
        } else {
            this.loggedIn = false;
        }
        localStorage.setItem('loggedIn', this.loggedIn);
        console.log(result);
    });
}}

I still get the same error.
How can I access router so that I can redirect to another page if result is true?

You are losing the context of your this variable, which is why this.router is undefined. Use arrow syntax to keep the context:

this.socket.on('login', (result) => { // <--- here
    if (result) {
        this.loggedIn = true;
        this.router.navigate(['/profile']);
    } else {
        this.loggedIn = false;
    }
    localStorage.setItem('loggedIn', this.loggedIn);
    console.log(result);
});

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