当我收到套接字事件drawMouse
&我的draw()
函数调用myVar
未定义。 为什么我无法从socket.on回调中访问this.myVar
?
import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
myVar:string;
constructor(){
this.socket = io("http://localhost:4300");
this.myVar = "hello"
}
ngOnInit() {
this.socket.on('drawMouse', function(data){
this.draw(data)
})
}
draw(){
//this variable is undefined
console.log(this.myVar);
}
}
答案 0 :(得分:3)
因为套接字回调中的 this.socket.on('drawMouse', (data)=>{
this.draw(data)
})
没有引用该组件。
尝试:
{{1}}