错误:无法找到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到诸如Arrays之类的Iterables。嵌套的JSON

时间:2018-01-22 17:42:53

标签: angular typescript ionic-framework

我正在尝试绑定数据,这是我在下面包含的嵌套Json文件。但是,我收到此错误。我是初学者,所以任何帮助都会非常感激。

错误:无法找到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到Iterables,例如Arrays。

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {
   weapons: any;
   errorMessage: string;
  constructor(public navCtrl: NavController, public rest: RestProvider) {

 }
 ionViewDidLoad() {
  this.getweapons();
}
 getweapons() {
   this.rest.getweapons()
      .subscribe(
        weapons => this.weapons = weapons,
        error =>  this.errorMessage = <any>error);
 }

  }

HTML

  <ion-content padding>
    <ion-list>
      <ion-item *ngFor="let c of weapons">
        <h2>{{c.weapon_category.weapons[0].name}}</h2>
      </ion-item>
    </ion-list>
  </ion-content>

服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
// import 'rxjs/add/operator/catch';
// import 'rxjs/add/operator/map';
@Injectable()
export class RestProvider {
  baseUrl:string = "http://localhost:3000";
  constructor(private httpClient : HttpClient) {
  }

  public getweapons(): Observable<{}> {
    return this.httpClient
      .get(this.baseUrl + '/categories')
      .pipe(
          map(this.extractData),
          catchError(this.handleError)
        );
      }

      private extractData(res: Response) {
        let body = res;
        return body || { };
      }

      private handleError (error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
          const err = error || '';
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
      }

}

的Json

{
  "weapon_category": {
    "weapons": [
        {
          "name": "AK",
        }
      ]
    }
}

1 个答案:

答案 0 :(得分:1)

武器是一个对象,因此你会收到这个明显的错误 Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

要解决此问题,您需要访问 weapons.weapon_category.weapons 才能获得数组

将模板更改为

 <ion-item *ngFor="let c of weapons?.weapon_category?.weapons">
        <h2>{{c.name}}</h2>
 </ion-item>