templateUrl display before data loaded

Hi All,

I have an Ionic 2 Component. It renders a html page. In the constructor, it fetches data in a promise. The html uses the data (personModel) and displays the values.

My problem is the html wants to render before the promise has completed getting the data, resulting in an error.

TypeError: self.context.personModel is undefined

How do I make sure the html waits for the data to load before it tries to render?

Thanks

html

<h2>{{personModel.firstName}}&nbsp;{{personModel.lastName}}</h2>

ts

@Component({
  templateUrl: 'build/pages/person/person.html',
})

constructor() {
    // promise that loads data
    this.utilityService.getLoggedInPerson().then((data: string) => {
       this.personModel = JSON.parse(data);
    }
}

You need to define the member variable straight away, and then assign the data to it, i.e:

personModel: any;

constructor() {
    // promise that loads data
    this.utilityService.getLoggedInPerson().then((data: string) => {
       this.personModel = JSON.parse(data);
    }
}
2 Likes

It doesn’t work in my case: personalModel will be initialized after template is rendered.

Does anybody have different solution?

At first I had the member defined without a type (so just personModel; ) You have to explicitly give the personModel a type of any. When I did that, it worked right away.

I completely disagree with all the recommendations of using any here. Type your properties properly and initialize them to viable dummy values. Moreover, the post above this is inaccurate. “I used any because it worked” is a weak justification in the first place, but in situations like that described by OP, it doesn’t even work. Templates don’t care about typing, and giving personModel a type of any would not fix the original problem. Assigning an empty object to it (personModel = {}) would.