代码之家  ›  专栏  ›  技术社区  ›  Cacoon

是否从服务接收到数组对象,但无法对其进行迭代?

  •  -1
  • Cacoon  · 技术社区  · 8 年前

    我有一个配方web应用程序,我有一个“添加配方”页面,其中一个子组件“添加配料”嵌套并在其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>
    

    然后,我添加了一个按钮,以确保从服务发送的数据实际以正确的格式接收等(如屏幕截图所示,当子组件添加成分时,它完美地发送了对象),但当我尝试将其与表一起显示时,出现了以下错误:

    找不到类型不同的支持对象“[对象对象]” “fawf”。NgFor仅支持绑定到数组等可扩展项。

    enter image description here

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

    2 回复  |  直到 8 年前
        1
  •  0
  •   Sam Clark-Ash    8 年前

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

    hack(val) {
      return Array.from(val);
    }
    
        2
  •  0
  •   Cacoon    8 年前

    这里找到了一个解决方法 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]);
      }
    }
    

    成功了