javascript - 为什么 myVar 未定义?

标签 javascript angular socket.io

当我收到我的套接字事件 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);
  }
}

最佳答案

因为套接字回调中的 this 没有引用组件。

尝试:

 this.socket.on('drawMouse', (data)=>{
          this.draw(data)
      })

关于javascript - 为什么 myVar 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533654/

相关文章:

html - 容器 div 不会调整到子 Angular 组件高度

css - Angular Material : displaying icons to the right of mat-chip

redirect - Angular 2 RC5 - 使用 Observable 重定向路由

node.js - 实时应用程序 - socket.io (node.js) 的替代方案

node.js - 我可以使用 Tsung 加载测试 Socket.io 应用程序吗?

javascript - 如何将backbone.js 与websockets/socket-io/nowjs 一起使用

javascript - npm WARN checkPermissions 缺少对/usr/local/lib/node_modules 的写入权限

JavaScript 添加事件监听器

javascript - 使用 PHP 更改 CSS 值

javascript - 使用 React 和一个 <div> id 的网页