首页 > 解决方案 > 使用 Ionic/Angular 在 HTML 中打印 Json 数据

问题描述

我正在使用 IONIC Angular 构建一个应用程序,并且我正在尝试以 HTML 格式打印结果。

从 console.log 它可以正常工作,但从视图中我无法打印数据

json接口

{
  "matches1": {
    "homeTeam": "Barcellona",
    "awayTeam": "Real Madrid",
   },
  "matches2": {
    "homeTeam": "PSG",
    "awayTeam": "Lione",
   }
}

主页.ts

export class HomePage {

  matches1: any;
  homeTeam1: any;
  awayTeam1: any;
  result1: any;

  private apiurl = 'https://myapi.xxx';

  constructor(private httpService: HttpClient) {
    this.getdata();
  }

  getdata() {
    this.httpService.get(this.apiurl).subscribe(res => {
        this.item = res['matches1']['homeTeam'];
        console.log(this.item); <-- this work in console log
    }, (err: HttpErrorResponse) => {
        console.log (err.message);
       }
      );
    }

}

主页 html

  <ion-item *ngFor="let item of items"> 
    {{item.homeTeam}}
  </ion-item>

谢谢!

标签: jsonangularionic-framework

解决方案


这应该做的工作:

export class HomePage {

  matches1: any;
  homeTeam1: any;
  awayTeam1: any;
  result1: any;
  items: any;

  private apiurl = 'https://myapi.xxx';

  constructor(private httpService: HttpClient) {
    this.getdata();
  }

  getdata() {
    this.httpService.get(this.apiurl).subscribe(res => {
        this.items = Object.keys(res).map(function(key, index) {
          return res[key];
        });
    }, (err: HttpErrorResponse) => {
        console.log (err.message);
       }
      );
    }

}


推荐阅读