【问题标题】:Error trying to diff '[object Object]'. Only arrays and iterables are allowed. (Ionic 3)尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象。 (离子 3)
【发布时间】:2018-10-11 16:25:33
【问题描述】:

我正在做一个项目,但我不断收到错误Error trying to diff '[object Object]'. Only arrays and iterables are allowed 我查找了错误,有两种方法可以做到这一点,更改传入数据(不可能)或“转换我的组件中的对象”。我需要做后者,但我找不到任何方法,因为我只是一个学生。以下是一些相关代码:

characters.ts

     apiUrl = 'https://swapi.co/api/people';

     getUsers() {
     return new Promise(resolve => {
     this.http.get(this.apiUrl)
     .subscribe(data => {
      resolve(data);
     }, err => {
     console.log(err);
    });
   });

home.ts

  users: any= [];

  constructor(public navCtrl: NavController, public restProvider: 
  CharactorsProvider) {
  this.getUsers();
 }


  getUsers() {
  this.restProvider.getUsers()
  .then(data => {
  this.users = data;
  console.log(this.users);
 });
 }

home.html

 <ion-list>
 <ion-item *ngFor="let user of users">
  <p>{{charactor.results}}</p>
 </ion-item>
 </ion-list>
</ion-content>

请在更改代码方面提供任何帮助,这将是一个巨大的帮助。我是 Ionic 的新手,刚接触几个星期,并且对它有基本的了解。

编辑:代码不在框中。 编辑 2:我正在使用的 API https://swapi.co/api/people/

【问题讨论】:

  • console.log(this.users) 输出什么?
  • 你把console.log(JSON.stringify(this.users));放进去时看到了什么
  • @BenWest Console.log 输出数组 {name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", ... }
  • @Sajeetharan 输出数组 {"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color ":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male","homeworld":"swapi.co/api/planets/1", } 等会在 post
  • 您需要来自服务器响应的可迭代(数组)。基本上你需要在响应中获取“结果”数组。

标签: html angular api ionic3 ngfor


【解决方案1】:

根据您在上面发布的 JSON,看起来您有一个对象而不是数组。

正如上面提到的错误"Error trying to diff '[object Object]'. Only arrays and iterables are allowed",你需要使用 ngFor 来迭代数组。

要么更改您的 API 以将响应作为数组发送,要么将对象推送到数组。

你在 ngFor 变量中也有问题

<ion-item *ngFor="let user of users">
  <p>{{user.name}}</p> //access each user object from array
 </ion-item>

EDIT

当我查看响应时,实际上您应该从响应中访问 results 属性,它是一个数组。

this.http.get('https://swapi.co/api/people/')
      .subscribe((res: Response) => {
        this.users = res.json().results; 
      }, error => {
        console.log(error);
        this.errorFromSubscribe = error;
});

HERE IS A WORKING STACKBLITZ

【讨论】:

  • 如果你确定 api 总是只返回一个对象,你可以这样做 this.users.push(data);
  • @JackCaltagirone 检查上面的工作堆栈闪电编辑
猜你喜欢
  • 2018-09-14
  • 2020-08-15
  • 1970-01-01
  • 2021-12-21
  • 2018-11-25
  • 2021-10-22
  • 2020-05-27
  • 2018-07-15
相关资源
最近更新 更多