首页 > 解决方案 > 如何在 ionic 的 ts 文件中使用来自 Api 的数据

问题描述

我想知道如何在同一个 ts 文件中使用从 API 获取的数据。我能够使用此数据并使用此代码在 HTML 中显示它。

loadAppInfo() {

  this.http.get('Here goes my url')
  .map(res => res.json())
  .subscribe(data => {
    this.AppInfo = data.records;
    console.log(data.records);
  },err => {
    console.log(err);
  });
}
<ion-option *ngFor="let data of AppInfo">{{ data.AppName }}</ion-option>

使用此代码,我可以毫无问题地以 HTML 格式显示数据。但我想将此单个数据设置为我的 ts 文件中的一个变量,然后使用它。

可能吗?

这是在控制台中打印 AppInfo 后数据的样子。 这是图像

提前致谢 :)

标签: htmlangularapitypescriptionic-framework

解决方案


您要做的是在订阅中调用一个方法。因此,当调用此方法时,您将确定数据已填充:

loadAppInfo() {

  this.http.get('Here goes my url')
  .map(res => res.json())
  .subscribe(data => {
    this.AppInfo = data.records;
    this.AppName = this.AppInfo.AppName; // add "public AppName;" declaration in your class
    console.log(data.records);
    this.computeWithFilledData();
  },err => {
    console.log(err);
  });
}

computeWithFilledData() {
    // use this.AppInfo here
}

推荐阅读