我正在尝试在一个开关内设置一个setTimeout,它位于一个foreach内部,位于一个函数内...
TypeError:undefined不是对象(评估'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
}
}
所有这些都得到了未定义的错误。
答案 0 :(得分:0)
写作时
.forEach(function(foundAction){
this
不再引用您的类,而是匿名函数。你应该使用箭头功能
.forEach(fundAction => {
并在setTimeout
中执行相同操作,以避免传递this
的引用。