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

1 Answer 1

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);
            }
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.