javascript - angular 2 settimeout 这是未定义的

标签 javascript angular settimeout

我正在尝试设置一个 setTimeout,在开关内,在 foreach 内,在函数内......

TypeError: undefined is not an object (evaluating 'this.Data')

我试过了

import { DataProvider } from '../xml-provider';
constructor(private Data: DataProvider) { }
items = this.Data.xmldata['step'];  //XML turned into array using 

initiateStepActions(){
    var actionsToTake = this.items[this.currentStep]['timed_actions'];
    if (actionsToTake){
        this.items[this.currentStep]['timed_actions'][0]['action'].forEach(function(foundAction){
          switch (type) {
            case 'customerchat':
              var MesgObject = {text : foundAction['_']};
              //setTimeout(() => {this.Data.broadcastCustomerChatMesg(MesgObject)}, Number(foundAction['$']['showAtSecond']));
              //setTimeout (() => this.Data.broadcastCustomerChatMesg(MesgObject), Number(foundAction['$']['showAtSecond']));
              //setTimeout ( (this.Data.broadcastCustomerChatMesg(MesgObject)).bind(this), Number(foundAction['$']['showAtSecond']));
              //setTimeout (this.Data.broadcastCustomerChatMesg(MesgObject), Number(foundAction['$']['showAtSecond']));
              setTimeout (function(this) { this.Data.broadcastCustomerChatMesg(MesgObject)}, Number(foundAction['$']['showAtSecond']));

              TypeError: undefined is not an object (evaluating 'this.Data.broadcastCustomerChatMesg')
              break;

            case 'supportchat':
              console.log('send a support chat message ');
              break;

            default:
              console.log('defaulted');
          } //end switch
    });// end foreach
  }
}

他们都得到了未定义的错误。

最佳答案

当你写的时候

.forEach(function(foundAction){

this 不再引用您的类,而是引用匿名函数。你应该使用箭头函数

.forEach(fundAction => {

并在 setTimeout 中执行相同操作以避免传递 this 的引用。

关于javascript - angular 2 settimeout 这是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197435/

相关文章:

javascript - 如何使用 javascript jquery 将具有多个 id 的数组制作为视频标签

javascript - 在 DATE 验证列中创建空值

javascript - mmenu.jquery 滑出菜单阻止 adsense 显示

angular - rxjs 和 WebStorm

javascript - 更改对象数组中的特定字段值 Angular 4

javascript - 在 for 循环中使用 setTimeout

javascript - ReactJS:setTimeout 无法在 map 内工作来渲染组件

javascript - 我应该有一个全局对象,javascript吗?

javascript - 有没有办法让 JS 引擎加载一个 .js 文件而不显式地从它导入一些东西?

JavaScript setTimeout 无法访问函数变量