【问题标题】:Array object received from service but cannot iterate through it?从服务接收的数组对象但不能遍历它?
【发布时间】:2017-10-11 00:32:46
【问题描述】:

我有一个食谱网络应用程序,我有一个“添加食谱”页面,其中包含一个嵌套并在其 HTML 中调用的子组件“添加成分”,如下所示:

<h2>Add {{addRecipeForm.controls.name.value}}</h2>
<form [formGroup]="addRecipeForm">
  ...
  <app-add-ingredient></app-add-ingredient>
  <hr>
  <button type="submit">Add new recipe</button> <button (click)="goBack()">Back</button> <button (click)="test()">check if array was caught</button>
</form>
<p>Recipe ingredient list (from service)</p>
<div *ngIf="ingredientList">
<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Quantity</th>
    <th>Units and Style</th>
  </tr>
  <tr *ngFor="let ingre of ingredientList">
    <td>{{ingre.ID}}</td>
    <td>{{ingre.name}}</td>
    <td>{{ingre.quantity}}</td>
    <td>{{ingre.unitsAndStyle}}</td>
  </tr>
</table>
</div>

然后我添加了一个按钮,以确保从服务发送的数据实际上是以正确的格式接收的(如屏幕截图所示,当子组件添加成分时,我得到它完美地发送对象)但是当我尝试呈现时如图所示,我收到此错误:

找不到不同类型的支持对象“[object Object]” '呵呵'。 NgFor 只支持绑定到 Arrays 等 Iterables。

我知道服务不是问题,因为我的“test()”函数只记录了数组及其所有内容,如屏幕截图所示。

【问题讨论】:

  • 控制台窗口截图中是否应该显示一些数组?我看到一个对象,其中名称 = 'fawf',ID = 20,但没有数组。数组将显示在方括号中,而不是大括号中。

标签: arrays angular loops iteration


【解决方案1】:

https://github.com/angular/angular/issues/6392 这似乎列出了一个类似的问题,他们通过做一个小的“hack”来解决这个错误。

hack(val) {
  return Array.from(val);
}

【讨论】:

    【解决方案2】:

    在这里找到解决方法Iterate over object in Angular

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'values',  pure: false })
    export class ValuesPipe implements PipeTransform {
      transform(value: any, args: any[] = null): any {
        return Object.keys(value).map(key => value[key]);
      }
    }
    

    成功了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-15
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多