簡體   English   中英

當socket.io發出“登錄”消息時,TypeError:無法讀取未定義的屬性“ navigate”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM