简体   繁体   中英

Cannot read property 'push' of undefined Angular/Typescript

I'm trying to add an array of Funcionarios objects into a Equipa object, but when i try to push a new Funcionarios it pops and this error TypeError: Cannot read property 'push' of undefined , i have gone over the code several times and initialized all variables, but it keeps always giving me the same error.

export class Funcionarios {
    id : Number;
    codFunc: Number;
    nomeFunc: string;

    constructor(codFunc: Number, nomeFunc: string) {
        this.codFunc = codFunc;
        this.nomeFunc = nomeFunc;
    }
}

export class Equipa {
    id : Number;
    codEquipa: Number;
    nomeEquipa: string;
    ocorFuncs: Funcionarios[] = [];

    constructor(id : Number, codEquipa: Number, nomeEquipa: string, funcs: Funcionarios[]) {
        this.id = id;
        this.codEquipa = codEquipa;
        this.nomeEquipa = nomeEquipa;
        this.ocorFuncs = funcs;
    }
}

export class TestComponent implements OnInit {

    equipa: Equipa = new Equipa(null, null, null, null);

    ngOnInit() {
        this.equipa.ocorFuncs.push(new Funcionarios(1, "qwe"));
        this.equipa.ocorFuncs.push(new Funcionarios(2, "asd"));
        this.equipa.ocorFuncs.push(new Funcionarios(3, "zxc"));
    }
}

Okay, so you see what you are truing to do right now.

You want to push value to the null , null have no push method. if you change this declaration line to

equipa: Equipa = new Equipa(null, null, null, []);

it will work fine, checked on stackblitz

The constructor for Equipa assigns ocorFuncs with whatever comes from the parameter funcs which in your case is null , and thus overrides the value you initialize the field with. You should check if the parameter is null and leave the default value if the parameter is null:

export class Equipa {
    id : Number;
    codEquipa: Number;
    nomeEquipa: string;
    ocorFuncs: Funcionarios[] = [];

    constructor(id : Number, codEquipa: Number, nomeEquipa: string, funcs: Funcionarios[]) {
        this.id = id;
        this.codEquipa = codEquipa;
        this.nomeEquipa = nomeEquipa;
        this.ocorFuncs = funcs || this.ocorFuncs;
    }
}

You create your Equipa object like so:

new Equipa(null, null, null, null);

The fourth argument, to initialize ocorFuncs is passed as null so:

this.equipa.ocorFuncs.push(new Funcionarios(3, "zxc"))

is invoking push on an object that has not been initialised correctly.

You are initializing your equipa with null values. So after calling new Equipa(null, null, null, null)

it is setting them inside the constructor as null

this.ocorFuncs = funcs;

try initializing it with an empty array

equipa: Equipa = new Equipa(null, null, null, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM