[英]When socket.io emits to 'login', TypeError: Cannot read property 'navigate' of undefined
我正在使用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發出“登錄”信息時,我都會在控制台上收到此錯誤
錯誤TypeError:無法讀取未定義的屬性“導航”
我更改了代碼,並從構造函數中初始化了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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.