如何在Angular 6中迭代json数据?

时间:2018-09-08 19:11:35

标签: angular angular6

我正在从事Angular 6项目。在我的项目中,我正在通过httpClient发出请求,通过该请求我获取json数据,但我不知道如何遍历此数据。如果有人知道解决方案,请提供帮助。

我的Json数据如下:

Json data

错误详细信息:

error

app.component.js

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'servicedemo';
  private url = "http://localhost/api.php";
  public apps: Applications[];

constructor(http: HttpClient) {
    http.get(this.url).subscribe(result => {
        this.apps = result as Applications[];
        console.log(this.apps);
    }, error => console.error(error));
}}

interface Applications {
    id: number;
    name: string
    age: number 
}

app.componenet.html

<div *ngFor="let item of apps">
    {{ item.name }}
 </div>

1 个答案:

答案 0 :(得分:1)

首先在其上使用Object.keys将对象转换为数组:

    http.get(this.url).subscribe(result => {
        const arr: Applications[] = Object.keys(result);
        this.apps = arr;
        console.log(data);
    }, error => console.error(error));

您还应该订阅onInit