gpt4 book ai didi

javascript - 当 socket.io 发出到 'login' 时,TypeError : Cannot read property 'navigate' of undefined

转载 作者:行者123 更新时间:2023-11-30 15:00:39 24 4
gpt4 key购买 nike

我正在使用 angular 4 和 socket.io 开发聊天应用程序。
这是我的代码

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

因此,每当 socket.io 发出“登录”信号时,我的控制台就会收到此错误
错误类型错误:无法读取未定义的属性“导航”
我更改了代码并从构造函数中初始化了router:

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

我仍然得到同样的错误。
如果 result 为真,我如何访问 router 以便重定向到另一个页面?

最佳答案

您正在丢失 this 变量的上下文,这就是 this.router 未定义的原因。使用箭头语法来保持上下文:

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

关于javascript - 当 socket.io 发出到 'login' 时,TypeError : Cannot read property 'navigate' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46584599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com