尝试区分“[object Object]"时出错.只允许使用数组和可迭代对象.(离子 3) [英] Error trying to diff '[object Object]'. Only arrays and iterables are allowed. (Ionic 3)

查看:28
本文介绍了尝试区分“[object Object]"时出错.只允许使用数组和可迭代对象.(离子 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,但我不断收到错误 Error 尝试 diff '[object Object]'.只允许使用数组和可迭代对象 我查找了错误,有两种方法可以做到,更改传入数据(不可能)或转换组件中的对象".我需要做后者,但我找不到任何方法,因为我只是一个学生.下面是一些相关的代码:

I'm doing a project and I keep getting the error Error trying to diff '[object Object]'. Only arrays and iterables are allowed I looked up the error and there are two ways to do it, change the incoming data(no possible) or "transform the object in my component". I need to do the latter, but I can't find any way how to as I'm only a student. Here's some of the relevant code:

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,才几个星期,对它有基本的了解.

Please any help with changing the code would be a huge help. I'm new to Ionic, only a few weeks in, and have a basic knowledge of it.

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

Code not in boxes. Edit 2: API I'm using https://swapi.co/api/people/

推荐答案

基于您上面发布的 JSON,看起来您拥有一个对象而不是数组.

Well based on the JSON you posted above, it looks like you have a Object instead of array.

如上面所述的错误尝试区分'[object Object]'时出错.只允许使用数组和可迭代对象"您需要使用ngFor对数组进行迭代.

As the error stated above "Error trying to diff '[object Object]'. Only arrays and iterables are allowed" you need array to iterate over using ngFor.

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

Either change your API to send the response as array, or push the object to an array.

你的 ngFor 变量也有问题

Also you have an issue in ngFor variable

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

编辑

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

When i looked in the response, actually you should access the results property from the response which is an array.

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

这是一个工作STACKBLITZ

这篇关于尝试区分“[object Object]"时出错.只允许使用数组和可迭代对象.(离子 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆