Ionic 2, Cannot read property 'x' of undefined in a template, how to?

Hello,

I am getting some data with a promise and trying to display it in a template, but i get Cannot read property 'x' of undefined.

Here is my code. this.someData.attributes will be undefined until the promise resolves, but how do i tell the view to display the data whenever that’s resolved?

export class SomePage {
    local: Storage = new Storage(LocalStorage);
    someData: Object;

    constructor(private app: App, private nav: NavController) {}

    ionViewDidEnter() {
        console.log('ionViewDidEnter');

        this.local.get('someData').then(resp => {
            this.someData= JSON.parse(resp);
            console.log(this.someData); // this works
        });
    }

    ngAfterViewInit() {
        console.log('ngAfterViewInit');
    }
}

in the view:

<h4 *ngIf="someData.attributes !== undefined">
    {{someData.attributes.x}}
</h4>

any ideas?

looks like the correct syntax is

<h4 *ngIf="someData">
    {{someData.attributes.x}}
</h4>

the correct one would be

<h4 *ngIf="someData?.attributes">
    {{someData.attributes.x}}
</h4>

i think.

the “?”-mark is like marking something as optional and only if this part is there evaluate the rest.

1 Like