[英]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. 我正在使用angular 4和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 所以每当socket.io发出“登录”信息时,我都会在控制台上收到此错误
ERROR TypeError: Cannot read property 'navigate' of undefined
错误TypeError:无法读取未定义的属性“导航”
I changed the code and initialised router
out of the constructor: 我更改了代码,并从构造函数中初始化了
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);
});
}}
I still get the same error. 我仍然遇到相同的错误。
How can I access router
so that I can redirect to another page if result
is true? 如果
result
为真,如何访问router
以便可以重定向到另一个页面?
You are losing the context of your this
variable, which is why this.router
is undefined. 您正在丢失
this
变量的上下文,这就是为什么this.router
未定义的原因。 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.