【问题标题】:angular 2 settimeout this is undefined角度 2 settimeout 这是未定义的
【发布时间】:2018-10-16 06:28:46
【问题描述】:

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

TypeError: undefined is not an object (evalating '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吗?
  • 添加了代码,希望它更有意义。

标签: javascript angular settimeout


【解决方案1】:

当你写作时

.forEach(function(foundAction){

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

.forEach(fundAction => {

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

【讨论】:

  • 它正在工作 .forEach((foundAction) => { 然后 setTimeout(() => { 成功了!
猜你喜欢
  • 2017-02-08
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2018-03-12
相关资源
最近更新 更多