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

问题描述

我想做什么:

我想过滤这些数组,看看是否有同时处于活动状态的日期。

这是我的代码

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 = [];
    }
}

解决方法

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

尝试

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);
    }