开发者问题收集

错误:无法读取未定义的属性“forEach”

2020-10-07
118

我想要做什么:

我想要过滤这些数组并查看是否有任何日期在同一时间处于活动状态。

这是我的代码:

loadAllAndCheckDates (recommendedSection: RecommendedSection): boolean {
        this.query()
            .subscribe((res: ResponseWrapper) => { this.fromDbRecommendedSections = res.json; }, (res: ResponseWrapper) => this.onError(res.json));

        return this.checkDates(recommendedSection);
    }

    checkDates (currentRecSec: RecommendedSection): boolean {

        this.fromDbRecommendedSections.forEach((recSecDB:RecommendedSection) =>{
            var dbActiveFrom = new Date(recSecDB.activeFrom);
            var dbActiveTo = new Date(recSecDB.activeTo);
            var currActiveFrom = new Date(currentRecSec.activeFrom);
            var currActiveTo = new Date(currentRecSec.activeTo);
             if(dbActiveFrom.getTime() === currActiveFrom.getTime()){
                this.isDouble = true;
             }if (dbActiveTo.getTime() === currActiveTo.getTime()){
                this.isDouble = true;
             }if(dbActiveFrom > currActiveFrom && dbActiveFrom < currActiveTo){
                 this.isDouble = true;
             }if(dbActiveTo > currActiveFrom && dbActiveTo < currActiveTo){
                 this.isDouble = true;
             }
        }, (res: ResponseWrapper) => this.onError(res.json));
        return this.isDouble;
    }

问题:

遗憾的是我在控制台中收到以下错误: 无法读取未定义的属性“forEach”

编辑:

以下是 fromDbRecommendedSection 的设置方式:

export class RecommendedSection implements BaseEntity {
    constructor(
        public id?: number,
        public activeFrom?: any,
        public activeTo?: any,
        public identification?: string,
        public recommendedSectionNames?: RecommendedSectionName,
        public recommendedSectionItems?: RecommendedSectionItem[],
    ) {
        this.recommendedSectionItems = [];
    }
}

1个回答

您应该在您的示例中同步处理数据,否则在填充 this.fromDbRecommendedSections 之前获取响应的延迟可能会太高。因此,当您返回 this.checkDates 时, this.fromDbRecommendedSectionsundefined

尝试

loadAllAndCheckDates (recommendedSection: RecommendedSection): boolean {
        this.query()
            .subscribe((res: ResponseWrapper) => {
                this.fromDbRecommendedSections = res.json; // needs to be an array
                this.checkDates(recommendedSection)
            }, (error:any) => console.log(error);
    }
JSmith
2020-10-07