我正在尝试设置一个 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/