【问题标题】:Angular 7: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as ArraysAngular 7:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2019-03-19 05:44:19
【问题描述】:

有一个从 http 请求填充的数据切换下拉菜单。

<div class="dropdown">
 <input #searchInput class="dropdown-toggle" type="text" id="dropdown-input" placeholder=" " autocomplete="off"
     (input)="handleChange(searchInput.value)"
     data-toggle="dropdown">

<ul class="dropdown-menu scrollable-menu" role="menu">
<ng-template [ngIf]="isAsync">
  <li class="dropdown-item" *ngFor="let d of asyncData$ | async">{{valueAttribute ? d[valueAttribute] : d }}</li>
</ng-template>

我在上面的代码中使用 Angular async 管道。我在下面尝试了。

  ngOnInit() {

    this.asyncData$ = this.searchTerms.pipe(
    // wait 300ms after each keystroke before considering the term
    debounceTime(300),

    // ignore new term if same as previous term
    distinctUntilChanged(),

    // switch to new search observable each time the term changes
    switchMap((term: string) => this.retrieveData(term)),
);

}

retrieveData(term: string) {
 let options: any = {};
 if (this.queryParamName) {
   options.params = {};
   options.params[this.queryParamName] = term;
 }
 return this.http.get(this.url, options);

}

Http调用返回成功响应,但出现以下错误。

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

欢迎提出任何建议。

谢谢!

【问题讨论】:

  • asyncData$ 中的数据是什么?这个错误意味着给定的值不是一个数组
  • 可能 asyncData$ 是一个对象而不是数组。这就是这个错误的情况。所以检查一下。
  • 还检查是否将预期的数组分配给返回的 json 中的属性。在这种情况下,您需要返回该属性的值。

标签: angular angular7


【解决方案1】:

似乎asyncData$ 发出的值是对象,而不是数组。您可以使用Object.keys()Object.values() 将它们转换为数组。

您也可以使用内置的键值管道:

<div *ngFor="let d of asyncData$ | async | keyvalue">
  {{ d.key }} {{ d.value }}
</div>

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 2019-04-04
    • 2020-10-17
    • 2017-10-15
    • 2018-07-19
    • 2017-02-10
    • 2020-03-28
    • 2018-04-07
    相关资源
    最近更新 更多