javascript - TypeScript: TypeError: Cannot read property 'push' of undefined - Stack Overflow

admin2025-04-18  0

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

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);
                }
            });
        });
    }
}
Share Improve this question asked Dec 8, 2015 at 10:01 StefanStefan 971 silver badge6 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

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);
            }
        });
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744964976a277142.html

最新回复(0)