matsch
matsch

Reputation: 491

Error: Cannot read property 'forEach' of undefined

What I want to do:

I want to filter through these arrays and see if there are any dates that are active at the same time.

This is my Code:

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

The Problem:

Sadly I get the following Error in the console: Cannot read property 'forEach' of undefined

Edit:

Here is how fromDbRecommendedSection is set up:

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

Upvotes: 0

Views: 125

Answers (1)

JSmith
JSmith

Reputation: 4808

you should process data synchronously in your example the delay of getting a response might be too high before you get this.fromDbRecommendedSections populated. So by the time you return this.checkDates this.fromDbRecommendedSections is undefined.

try

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

Upvotes: 1

Related Questions