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

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

我看过类似的问题,但其中 none 对我有帮助。 我将收到如下对象:

[
  {
    "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.

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

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

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

如果仍然显示与类型相关的错误,请在订阅参数对象上添加 any/RelevantModel 类型。

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

中删除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() returns 订阅,不是响应值。 响应值由传递给 subscribe(...)

的回调分配

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

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

请注意我是如何不小心调用 .json 的,就像一个变量而不是一个方法。

将其更改为:

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

成功了。

您可以将书籍(第 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);
    });
}

在您的 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集合的名称。请尝试上面的代码,我相信它会起作用。

我的解决方案是为 return 属性对象的值数组

创建一个管道
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> 

我遇到了同样的问题

我的初始json

{"items":

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

我已经在 []

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

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

我也遇到了同样的问题。这就是我解决问题的方法。 首先,当发生错误时,我的数组数据来自数据库,就像这样 --,

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

确保您的数据是一个数组,而不是一个带有数组的对象。只有数组看起来像这样 --,

(5) [{…}, {…}, {…}, {…}, {…}]

它解决了我的问题。

this.requests=res 此处您尝试将以下响应分配给对象,

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

因为对象格式与响应格式不同,您必须从响应中分配 res.body 部分以获得所需内容。

迭代具有如下 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>

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

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

在您使用 spring 引导时使用 Angular ;确保是否创建默认值

你应该使用异步管道。文档:https://angular.io/api/common/AsyncPipe

例如:

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

只需将 var 声明为您保存数据的 array,它对我有用。

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

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

对于通过 Google 到达这里的任何其他遇到此问题的人,请检查 *ngFor 指令的主机元素是否准确。我的意思是,我遇到了这个错误并花了很长时间研究修复,然后才意识到我已经将 *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>

事后看来,我知道这是一个明显的错误,但我希望这里的答案可以避免有人像我现在这样头痛。

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

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

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

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

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

JSON.parse(result.arrayOfObjects)

这是解决方案。

当您从数据库接收数组时。并且您将数组数据存储在变量中,但变量定义为对象。这次你会报错。

我正在从数据库接收数组,并将该数组存储在变量 '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;
   })
  }

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>

对我来说,当我将索引添加到 *ngFor 时错误就解决了。

<tr *ngFor = "let element of element_list; let i=index">
             <td>{{element.id}}</td>
             <td>{{element.status}}</td>
             <td>{{element.name}}</td>
 </tr>

我不知道是否有人会得到和我一样的东西,我也不知道为什么会这样(也许是一个错误?),但我实际上遇到了这个错误,因为只是因为我们试图创建angular 覆盖的 ComponentPortal,如下所示:

const smartfillPortal = new ComponentPortal(
  SmartFillModalComponent,
  this.viewContainerRef,
  {
    get: () => this.smartfillOverlayRef,
  }
);

改为

const smartfillPortal = new ComponentPortal(SmartFillModalComponent);

出于某种原因修复了它(我猜我还遗漏了一些关于覆盖的信息?)。

奇怪的是,在覆盖代码中甚至是这样的:

<div class="flex" *ngFor="let i of [1,2,3]; let i = index">
  <span>hi there</span>
</div>

会导致

Error: Cannot find a differ supporting object '1,2,3' of type 'object'. NgFor only supports binding to Iterables such as Arrays.