【发布时间】:2016-11-10 17:28:24
【问题描述】:
当我得到我的套接字事件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);
}
}
【问题讨论】:
-
你确定
draw真的被调用了吗?这似乎不太可能。
标签: javascript angular socket.io