Ionic/Angular Pushing object to Array Object

Viewed 536

I am trying to push an Object with values to an Array but I always get null is not an object in the console. But when I console.log the object it is filled and not null so why can't I push it into the array?

            let obj: Lektion;
            obj = {
                LektionID: data2.string[0],
                Date: data2.string[1],
                StudentID: data2.string[2],
                Name: data2.string[3],
                Status: (data2.string[4] !== '0'),
                TeacherID: data2.string[5]
            };
            console.log(obj);
            this.Lektionen.push(obj);

Output

2 Answers

I think you got confuse on variable and interface. Lektion is an interface define it's as a variable and try to push it into that.

   let Lektionen = [];
    const data2= {string:[1,2,3,4,5,6]};

    let obj:Lektion = {
                LektionID: data2.string[0],
                Date: data2.string[1],
                StudentID: data2.string[2],
                Name: data2.string[3],
                Status: (data2.string[4] !== '0'),
                TeacherID: data2.string[5]
            };
            this.Lektionen.push(obj);

            console.log(Lektionen); //will print the object

Have you initialized this.Lektionen? Try initializing it prior pushing the object.

this.Lektionen = [];
this.Lektionen.push(obj);

Ideally, initialize it where you have declared the variable or in the function where you are going to push items in the array.

Related