私のソケットイベントを取得するときdrawMouse
&私のdraw()
関数が呼び出されますmyVar
は未定義です。 socket.onコールバックからthis.myVar
にアクセスできないのはなぜですか?なぜ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);
}
}
と呼ばれていますか?そうは思わない。 –
ほとんどの場合、[コールバック内の正しい 'this'/contextにアクセスするにはどうすればいいですか?](http://stackoverflow.com/q/20279484/218196) –