【问题标题】:TypeError: Cannot read property 'emit' of undefined angularTypeError:无法读取未定义角度的属性“发射”
【发布时间】:2018-05-23 14:06:00
【问题描述】:

我在调用 setInterval 函数时遇到了困难。 请找到下面的代码 game.component.ts

import {Component, EventEmitter, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
   @Output() raiseEvent: EventEmitter< {currentEvent: number} > = new EventEmitter< {currentEvent: number} >();
  currentEventCount = 1;
  constructor() { }

  ngOnInit() {
  }

  StartGame() {
    setInterval( function () {
      this.raiseEvent.emit({currentEvent : this.currentEventCount++});
    }, 1000, this.raiseEvent);
  }
}

根据错误消息,我认为它试图在 setInterval 范围内查找 raiseEvent,那么如何在 setInterval 中调用此函数?

【问题讨论】:

  • 问题是 scope 。所以将你的 setInterval 更改为 setInterval( () =&gt;{ this.raiseEvent.emit({currentEvent : this.currentEventCount++}); }, 1000, this.raiseEvent);

标签: angular


【解决方案1】:

您应该使用 arrow function 来获取其中 this 的值

  • ES6 箭头函数语法使用“词法作用域”来确定“this”的值应该是什么。词法作用域是一种奇特的方式 说它使用周围代码中的“this”...... 包含有问题的代码。

  • 箭头函数是匿名的,会改变 this 在函数中的绑定方式。

  • 箭头函数简化了函数范围和 this 关键字

所以,setInterval 变为:

 StartGame() {
    setInterval(() => {
      this.raiseEvent.emit({currentEvent : this.currentEventCount++});
    }, 1000, this.raiseEvent);
  }

没有 ES6 你应该这样做:

StartGame() {
    let self = this;
    setInterval( function () {
      self.raiseEvent.emit({currentEvent : self.currentEventCount++});
    }, 1000, self.raiseEvent);
  }

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多