Issiues使用HTTP检索数据并在ionic中显示

时间:2018-08-08 07:01:46

标签: angular ionic-framework ionic3

我正在尝试使用ionic将我的JSON数据显示在应用程序中。

尝试输出数据时出现以下错误:

错误错误:“未捕获(承诺):错误:找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到可迭代对象,例如数组。

我的数据如下:

{
  "1": {
    "name": "John",
    "lastname": "Jonson",
    "email": "example@example.com",
    "image": ""
  },
  "5": {
    "name": "Peter",
    "lastname": "Parker",
    "email": "example@example.com",
    "image": ""
  },
  "8": {
    "name": "Joe",
    "lastname": "Lo",
    "email": "example@example.com",
    "image": ""
  },
}

我的HTML代码:

<ion-list *ngFor="let user of users">
    <ion-item>{{ user.name}}</ion-item>
</ion-list>

最后是js代码:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

    users: Observable<any>;

    usersList = [];

    constructor(public navCtrl: NavController, public httpClient: HttpClient) {

        this.users = this.httpClient.get('http://example.com/api/user');

        this.users.subscribe(data => {
            this.usersList = data,
             console.log(data);
        });
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用键将数据转换为对象数组。

Object.keys(yourData).forEach(value=>{ this.users.push({Key: value, User: data[value]})})

和如下模板:

<ion-list *ngFor="let user of users">
   <ion-item>{{ user.User.name}}</ion-item>
</ion-list>

答案 1 :(得分:0)

NgFor仅支持绑定到数组等Iterable。

所以让您的数据看起来像这样。

const myData = [
  {
    "name": "John",
    "lastname": "Jonson",
    "email": "example@example.com",
    "image": ""
  },
  {
    "name": "Peter",
    "lastname": "Parker",
    "email": "example@example.com",
    "image": ""
  },
  {
    "name": "Joe",
    "lastname": "Lo",
    "email": "example@example.com",
    "image": ""
  },
]

有关数组https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array

的更多信息