【问题标题】:Why is myVar undefined?为什么 myVar 未定义?
【发布时间】: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);
  }
}

【问题讨论】:

标签: javascript angular socket.io


【解决方案1】:

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

试试:

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

【讨论】:

  • @FelixKling 哦,我没有意识到这一点,怎么会这样? :D
  • 不知道 ;) 也许我误解了文字。
  • @echonax 有效。我猜这是因为尝试使用 es6 作用域,但没有使用新的函数语法,对吗?
  • @JustinYoung 完全正确。虽然您是否真的成功调用了该方法,但我们有点困惑。
  • @echonax 是的,它正在调用该方法,但是当我在方法调用中注销 myVar 的值时,它是未定义的。猜猜这只是越界了。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 2021-07-22
  • 2021-07-18
  • 2012-06-21
  • 2022-01-05
  • 2017-10-10
相关资源
最近更新 更多