Display data in template after it's loaded from Promise

Hi there, I’m using File plugin function readAsText( ) to convert my JSON file to string, then parse it to object and simply store it in a local variable which i then want to display in HTML template. Problem is the function readAsText() returns a Promise so when im displaying the variable its still undefined and data hasnt loaded yet.

My home.ts:

import { Component } from '@angular/core';
import { NavController} from 'ionic-angular';
import { File } from '@ionic-native/file';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})

export class HomePage {
    object: any;

    constructor(
        public navCtrl: NavController,
        public file: File,
    ) {
        // process that returns string, parses it into object and saves it into variable "object"
        this.file.readAsText("file:///android_asset/www/assets/json", "Choosing_Values.json")
        .then( result => {
            this.object = JSON.parse(result);
            console.log("Object: ", this.object);           // data is loaded
        }).catch( err => console.error("file wasnt read", err));
      }

And my HTML template:

<ion-content>
...

<p>Object: {{object}}</p>     <!-- the data is still undefined because the promise hasnt assigned the value in time-->

...
</ion-content>

My question is, how can I “wait” for the promise to finish loading the data, and display the variable only after it contains the object with the data ?

Thanks for your replies !

1 Like

I’m not going to answer this directly because I feel it leads to suboptimal UX. Instead of waiting, initialize the property to something like “loading…” or pop a loading indicator. Also, please give your properties both types (not any) and descriptive names (not object or data).