Cannot read property 'X' of undefined (onPageLoaded)


#1

Why when I try to set a property in the onPageLoaded event, I get the error:

Cannot read property ‘X’ of undefined

If I do this in the constructor, it works fine. I don’t want my app to execute this action everytime and as much as I’ve read, the onPageLoaded would be the appropriate event for that as it is called only once.

What am I missing?

Here is my code:

import {Component} from "@angular/core";
import {SubjectsViewModel} from "./subjects.viewmodel";
import {SubjectsService} from "./subjects.service";

export interface ISubjectsComponentScope {
    subjectsViewModel: SubjectsViewModel;
}

@Component({
    templateUrl: "build/users/sus/subjects/subjects.html",
    providers: [SubjectsService]
})
export class SubjectsComponent implements ISubjectsComponentScope {
    constructor(private subjectsService: SubjectsService) {
    }

    public subjectsViewModel: SubjectsViewModel;

    protected onPageWillEnter(): void {
        this.subjectsService.getSubjects()
            .then(subjects => {
                this.subjectsViewModel = new SubjectsViewModel("Title", subjects);
            });
    }
}

#2

In your code, you are using “onPageWillEnter”, not “onPageLoaded”.


#3

both don’t work.

It works tho, if I do so:

protected onPageWillEnter(): void {
    this.subjectsViewModel = new SubjectsViewModel("", {}); // THAT IS THE TRICK
    this.subjectsService.getSubjects()
        .then(subjects => {
            this.subjectsViewModel = new SubjectsViewModel("Title", subjects);
        });
}

#4

Can you, please, post your template here?


#5

As you are doing now (although I would do it as an assignment to the property or in the constructor), I think setting up a dummy value early is your best option. You can also guard accesses to the property with the Elvis operator, but I prefer to centralize it by initializing a dummy.