离子2 - 从Promise

时间:2017-06-30 14:25:10

标签: javascript angular asynchronous promise ionic2

我使用文件插件函数readAsText()将我的JSON文件转换为字符串,然后将其解析为对象并将其存储在本地变量中,然后我想在HTML模板中显示该变量。问题是函数readAsText()返回一个Promise,因此当我显示变量时,它仍然未定义且数据尚未加载。

我的家。:

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 wasn't read", err));
      }

我的HTML模板:

<ion-content>
...

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

...
</ion-content>

我怎样才能等待&#34;承诺完成加载数据,并仅在包含带有数据的对象后显示变量?

1 个答案:

答案 0 :(得分:0)

您可以检查变量是否已定义:

<p *ngIf="object">Object: {{object.COMPANY.COPMANY_NAME}}</p>

或使用elvis运营商:

<p>Object: {{object?.COMPANY.COPMANY_NAME}}</p>

在组件中:

export class HomePage {
    object: any = null;
}