找不到'对象'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到诸如Arrays之类的Iterables

时间:2016-10-02 16:56:14

标签: angular angular-template

我看了类似的问题,但没有一个帮助过我。 我将收到如下对象:

[
  {
    "id": 1,
    "name": "Safa",
    "email": "neerupeeru@mail.ee",
    "purpose": "thesis",
    "programme": "Software Engineering",
    "year": 2016,
    "language": "Estonian",
    "comments": "In need of correcting a dangling participle.",
    "status": "RECEIVED"
  },
  {
    "id": 2,
    "name": "Safa",
    "email": "neerupeeru@mail.ee",
    "purpose": "thesis",
    "programme": "Software Engineering",
    "year": 2016,
    "language": "Estonian",
    "comments": "In need of correcting a dangling participle.",
    "status": "RECEIVED"
  },
  {
    "id": 3,
    "name": "Salman",
    "email": "neerupeeru@mail.ee",
    "purpose": "thesis",
    "programme": "Software Engineering",
    "year": 2016,
    "language": "Estonian",
    "comments": "In need of correcting a dangling participle.",
    "status": "RECEIVED"
  }
]

这是我的http服务接收它:

getRequest(){
        return this._http.get("http://consultationwebserver.herokuapp.com/requests").map(res => res.json());
    }

最后,在我用这种方式调用服务:

requests;
    constructor(private _http:requestService){}
    ngOnInit(){
        this.requests=this._http.getRequest().subscribe(res=>this.requests=res);
    }

不幸的是,当页面加载时会抱怨:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

那么,这段代码出了什么问题?

19 个答案:

答案 0 :(得分:22)

在进行this.requests=调用时,您无需使用get(然后requests将有可观察的订阅)。您将在可观察的success中获得响应,因此设置成功的requests值是有意义的(您已经在做了)。

this._http.getRequest().subscribe(res=>this.requests=res);

答案 1 :(得分:11)

中删除this.requests
ngOnInit(){
  this.requests=this._http.getRequest().subscribe(res=>this.requests=res);
}

ngOnInit(){
  this._http.getRequest().subscribe(res=>this.requests=res);
}

this._http.getRequest()返回订阅,而不是响应值。 响应值由传递给subscribe(...)

的回调指定

答案 2 :(得分:7)

在您的JSOn文件中,请进行以下更改。

 {
    "data":
    [
      {
        "id": 1,
        "name": "Safa",
        "email": "neerupeeru@mail.ee",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      },
      {
        "id": 2,
        "name": "Safa",
        "email": "neerupeeru@mail.ee",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      },
      {
        "id": 3,
        "name": "Salman",
        "email": "neerupeeru@mail.ee",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      }
    ]
    }

之后:

 this.http.get(url).map(res:Response) => res.json().data);

数据实际上是json文件的tge集合的名称。请尝试上面的代码,我相信它会起作用。

答案 3 :(得分:5)

您可以将图书(第2行)声明为数组:

  title: any = 'List of books are represted in the bookstore';
  books: any = []; 
  constructor(private service:  AppService){
  }

  ngOnInit(){
    this.getBookDetails();
  }

  getBookDetails() {
    this.service.getBooks().subscribe(books => {
      this.books = books.json();
      console.log(this.books);
    });
  }

答案 4 :(得分:4)

我遇到了同样的错误,因为我已经映射了这样的HTTP响应:

this.http.get(url).map(res => res.json);

请注意我是如何意外地将.json称为变量而不是方法。

将其更改为:

this.http.get(url).map(res => res.json());

做了这个伎俩。

答案 5 :(得分:4)

我的解决方案是创建一个Pipe来返回values数组或propierties对象

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {

  // El parametro object representa, los valores de las propiedades o indice
  transform(objects : any = []) {
    return Object.values(objects);
  }
}

模板实施

<button ion-item *ngFor="let element of element_list | valueArray" >
    {{ element.any_property }}
</button> 

答案 6 :(得分:3)

对于通过Google到达此问题的其他任何人,请检查*ngFor指令的host元素是否正确。这样,我的意思是我遇到了这个错误,花了很长时间研究修补程序,然后才意识到我将*ngFor放在了ng-template元素上,而不是我想重复的组件上。

不正确

<ng-template *ngFor=let group of groups$ | async" ...>
  <my-component [prop1]="group.key" ... </my-component>
<\ng-template>

正确

<my-component *ngFor=let group of groups$ | async" [prop1]="group.key" ... </my-component>

我知道这是事后看来很明显的错误,但是我希望这里的答案可以减轻我现在的头痛。

答案 7 :(得分:2)

要遍历具有以下json格式的对象

{
  "mango": { "color": "orange", "taste": "sweet" }
  "lemon": { "color": "yellow", "taste": "sour" }
}
  1. 将其分配给变量

    let rawData = { "mang":{...}, "lemon": {...} }

  2. 创建一个空数组来保存值(或键)

    let dataValues = []; //For values

    let dataKeys = []; //For keys

  3. 遍历键并将值(和键)添加到变量

    for(let key in rawData) { //Pay attention to the 'in' dataValues.push(rawData[key]); dataKeys.push(key); }

  4. 现在您有了可以在* ngFor或for循环中使用的键和值数组

    for(let d of dataValues) { console.log("Data Values",d); }

    <tr *ngFor='let data of dataValues'> ..... </tr>

答案 8 :(得分:2)

我有同样的问题。这是我如何解决问题。 首先发生错误时,我的数组数据就像这样来自DB,

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
        <h3>Tabs Example</h3>

        <div class="tab">
          <button class="tablinks" onclick="openCity(event, 'tab1')">London</button>
          <button class="tablinks" onclick="openCity(event, 'tab2')">Paris</button>
          <button class="tablinks" onclick="openCity(event, 'tab3')">Tokyo</button>
        </div>

        <div id="tab1" class="tabcontent">
          <h3>London</h3>
          <p>London is the capital city of England.</p>
        </div>

        <div id="tab2" class="tabcontent">
          <h3>Paris</h3>
          <p>Paris is the capital of France.</p> 
        </div>

        <div id="tab3" class="tabcontent">
          <h3>Tokyo</h3>
          <p>Tokyo is the capital of Japan.</p>
        </div>
    </div>

确保您的数据是ARRAY,而不是带有数组的OBJECT。只有数组看起来像这样 - ,

{brands: Array(5), _id: "5ae9455f7f7af749cb2d3740"} 

它解决了我的问题。

答案 9 :(得分:2)

我遇到了同样的问题

我最初的json

{"items":

         [
           {"id":1,
            "Name":"test4"
           },
           {"id":2,
            "Name":"test1"
           }
         ]
}

我在[]

中更改了我的json
[{"items":

         [
           {"id":1,
            "Name":"test4"
           },
           {"id":2,
            "Name":"test1"
           }
         ]
}]

答案 10 :(得分:1)

this.requests=res在这里,您尝试为对象分配以下响应,

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK",
"url":"xyz","ok":true,"type":4,"body":[{}]}

由于对象格式与响应格式不同,因此必须从响应中分配res.body部分以获取所需的内容。

答案 11 :(得分:1)

<ul>
<li *ngFor = "let Data of allDataFromAws  | async">
  <pre> {{ Data | json}}</pre>
</li>
</ul>

使用异步将allDataFromAws转换为数组对象。...

答案 12 :(得分:1)

您应该使用异步管道。 Doc:https://angular.io/api/common/AsyncPipe

例如:

<li *ngFor="let a of authorizationTypes | async"[value]="a.id">
     {{ a.name }}
</li>

答案 13 :(得分:0)

在Angular中使用spring boot;确保是否创建默认

答案 14 :(得分:0)

只需将 var 声明为保存数据的数组即可,

listingdata:Array<any> = [];
this.listingdata = data.results.rows;

并在html页面上循环列表数据

答案 15 :(得分:0)

***********将结果解析为JSON对象:JSON.prase(result.arrayOfObjects)***********

遇到此问题后,我来到了此页面。因此,我的问题是服务器正在以字符串形式发送对象数组。就像这样:

从服务器获取结果后在控制台上打印结果时,它是字符串:

'arrayOfObject': '[
                  {'id': '123', 'designation': 'developer'},
                  {'id': '422', 'designation': 'lead'}
               ]'

因此,我必须从服务器获取此字符串后将其转换为JSON。使用方法来解析从服务器收到的结果字符串:

JSON.parse(result.arrayOfObjects)

答案 16 :(得分:0)

这是解决方案。

从数据库中接收阵列时。并且您将数组数据存储在变量中,但该变量定义为对象。这次您会得到错误。

我正在从数据库接收数组,并将该数组存储在变量“ bannersliders”中。 “ bannersliders”类型现在为“ any”,但是如果您写“ bannersliders”则是一个对象。就像bannersliders:any = {}。因此,这一次您将数组数据存储在对象类型变量中。所以你发现了这个错误。

因此,您必须编写“ bannersliders:any;”之类的变量。或“ bannersliders:any = []”。

我在这里举一个例子。

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
bannersliders:any;
  getallbanner(){
    this.bannerService.getallbanner().subscribe(data=>{
      this.bannersliders =data;
   })
  }

答案 17 :(得分:0)

Store that objects into Array  and then iterate the Array
export class AppComponent {

 public obj: object =null;
 public myArr=[];

  constructor(){

    this.obj = {
      jon : {username: 'Jon', genrePref: 'rock'},
      lucy : {username: 'Lucy', genrePref: 'pop'},
      mike : {username: 'Mike', genrePref: 'rock'},
      luke : {username: 'Luke', genrePref: 'house'},
      james : {username: 'James', genrePref: 'house'},
      dave : {username: 'Dave', genrePref: 'bass'},
      sarah : {username: 'Sarah', genrePref: 'country'},
      natalie : {username: 'Natalie', genrePref: 'bass'}
  }
  }
  ngOnInit(){
    this.populateCode();
  }

  populateCode(){
    for( let i in this.obj) {   //Pay attention to the 'in'
    console.log(this.obj[i]);
    this.myArr.push(this.obj[i]);
  }
  }
 }



<div *ngFor="let item of myArr ">
    {{item.username}}
    {{item.genrePref}}
  </div>

答案 18 :(得分:-1)

requests = [];


this.requests[0] =this._http.getRequest().subscribe(res=>this.requests=res);

*ngFor="let product of requests[0]"