简体   繁体   English

'this'在类成员上返回未定义

[英]'this' is returning undefined on a class member

When I instantiate this class, upon calling the init() function, I'm getting an undefined. 当我实例化此类时,调用init()函数时,我得到的是未定义的。 But inside emit('updateRoomsRequest') callback, I'm able to console log this.roomsData and see the values received through the socket connection. 但是在emit('updateRoomsRequest')回调内部,我可以控制台记录this.roomsData并查看通过套接字连接接收的值。

export class LoginService {
    roomsData: string[];
constructor(private socket: Socket) {}

init(connect: string): string[]{
    this.socket.on(connect, () => {
        this.socket.emit('updateRoomsRequest', {}, (data: string[]) => {
            this.roomsData = data;
            console.log(this.roomsData); //this is logging data correctly
        });
    });

    return this.roomsData; //this is returning undefined
}
}

this is the instantiation : 这是实例化:

export class LoginComponent implements OnInit {
    rooms: string[];
    constructor(private LoginPageService: LoginService) {}

    ngOnInit() {
        this.rooms = this.LoginPageService.init('connect');
        console.log(this.rooms); //undefined as well
    }

    }

Its about the order of execution. 它关于执行顺序。 Line A executes before Line B: A行在B行之前执行:

this.socket.on(connect, () => {
    this.socket.emit('updateRoomsRequest', {}, (data: string[]) => {
        this.roomsData = data; // LINE B
    });
});

return this.roomsData; // LINE A

And therefore it is undefined at LINE A. 因此在LINE A中未定义。

FIX 固定

Use callbacks, or promises or observables to chain your async code 🌹 使用回调或Promise或Observable链接您的异步代码🌹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM