0
votes

I'm trying to make an application with Angular 2. Now I ran into a problem which I can't solve.

One of the functions of an array should be push(object: T);

I defined an array of an object that I made. But when I try to add values to this array I receive the following error: TypeError: Cannot read property 'push' of undefined.

One of the main causes of this error is people forgetting to define their array. But I'm defining it, I tried it in multiple ways but still the same error.

export class Home {

    activeDossiers: Array<Dossier> = new Array();
    //Also tried:
    //activeDossiers: Dossier[] = [];
    //activeDossiers = [];
    //activeDossiers: Array<Dossier> = [];

    constructor() {
        var dossierApi = new DossierApi();
        dossierApi.getActiveDossiers().then((dossiers) => {
            dossiers.forEach(function (obj, i) {
                console.log(obj);
                if(obj.dossierType === Values.Visible) {
                    this.activeDossiers.push(obj);
                }
            });
        });
    }
}
1

1 Answers

4
votes

You are using the anonymous function() syntax for the callback; this syntax does NOT preserve the this. Instead do:

        dossiers.forEach((obj, i) => { // IMPORTANT PART HERE!!!
            console.log(obj);
            if(obj.dossierType === Values.Visible) {
                this.activeDossiers.push(obj);
            }
        });