我正在使用文件插件函数readAsText()
将我的 JSON 文件转换为字符串,然后将其解析为对象并简单地将其存储在局部变量中,然后我想在 HTML 模板中显示。问题是返回 Promise 的函数readAsText()
因此当我显示变量时,它仍未定义并且数据尚未加载。
我的家:
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>
我怎样才能"等待"承诺完成加载数据,并仅在变量包含带有数据的对象后显示变量?
您可以检查变量是否已定义:
<p *ngIf="object">Object: {{object.COMPANY.COPMANY_NAME}}</p>
或使用猫王运算符:
<p>Object: {{object?.COMPANY.COPMANY_NAME}}</p>
在组件中:
export class HomePage {
object: any = null;
}