【问题标题】:"Cannot find a differ supporting object '[object Object]' of type 'object'. ..." [duplicate]“找不到'object'类型的不同支持对象'[object Object]'。......” [重复]
【发布时间】:2019-06-13 01:21:02
【问题描述】:

我想显示name,但将_id 的值保存为mat-select。 并将其值保存在selectedIngridient 中,用于选择选项。

我明白了:

“找不到类型为‘object’的不同支持对象‘[object Object]’。NgFor 仅支持绑定到 Iterables,例如数组。”

但我正在查看不同的帖子(例如:Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays),无法找出错误。

我做错了什么?

斯塔克利茨:

https://stackblitz.com/edit/angular-l6yvgd?file=src/app/app.module.ts

初始化:

  import { Observable } from 'rxjs/internal/Observable';
  allIngridients: Observable<Ingridient[]>;
  selectedIngridient: Ingridient;

数据层:

    export class Ingridient {
    _id: string;

    name: string;// todo: Übersetzungen
    barCode?: Barcode;

    constructor() {
        this._id = UUID.UUID();
    }
}

标记:

      <mat-form-field>
            <mat-select placeholder="Select an ingridient" [(value)]="selectedIngridient">
              <mat-option *ngFor="let ingridient of allIngridients" [value]="ingridient._id">
                {{ingridient.name}}
              </mat-option>
            </mat-select>
          </mat-form-field>

填写allIngridients(来电constructor):

  inlineFunction_IngridientsNumberAndUnits_Ingridient(recipeId: string, anzahl: number): Ingridient[] {
    let result: Ingridient[] = [];

    for (let i_result = 0; i_result < anzahl; i_result++) {

      // todo: später mit recipe
      const tag: Ingridient = new Ingridient(recipeId);

      // Code
      tag.name = "Unit_" + (i_result + 1);
      tag.name = "BarCodes_" + (i_result + 1);

      // todo: changed
      this.allIngridients.subscribe(current => {
        current.push(tag);
      })

      result.push(tag);
    }

    return result;
  }

【问题讨论】:

  • 我正在为您撰写答案,但 Jota 将其标记为 dup。

标签: angular typescript


【解决方案1】:

下面的行不是数组,这就是你不能迭代它的原因。持有数组是可观察的。您需要订阅并将结果分配给数组,然后对其进行迭代。

allIngridients: Observable&lt;Ingridient[]&gt;;

或者使用| async管道:

<mat-option *ngFor="let ingridient of allIngridients | async" [value]="ingridient._id">

【讨论】:

  • 但我得到了一个订阅:` this.allIngridients.subscribe(current => { current.push(tag); }), its different ? When I use | async` 我没有收到任何错误,但没有任何显示...
  • @StartingAgain 你试过使用异步管道吗?
  • @StartingAgain 你确实订阅了,但不是拉你而是推。您需要使用异步管道或将订阅结果分配给 array 并遍历该数组。
  • 我正在尝试stackblitz.com/edit/angular-l6yvgd?file=src/app/app.module.ts,这可能有帮助吗?
  • “你确实订阅了,但不是拉你而是推。”,是的,因为我想用一些数据填充它......
猜你喜欢
  • 1970-01-01
  • 2019-09-15
  • 2021-11-20
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多