angular - Angular 7:找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays
问题描述
有一个从 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异步管道。我在下面尝试过。
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$
是对象,而不是数组。Object.keys()
您可以使用,将它们转换为数组Object.values()
。
您还可以使用内置的键值管道:
<div *ngFor="let d of asyncData$ | async | keyvalue">
{{ d.key }} {{ d.value }}
</div>