gpt4 book ai didi

javascript - angular 2 settimeout 这是未定义的

转载 作者:太空狗 更新时间:2023-10-29 19:32:57 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com