angular - Angular/Typescript 找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays
问题描述
我正在使用角度
尝试调用 api 并从中检索数据,但它会引发此错误。
core.js:4352 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我的服务看起来像
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { User } from '../Models/user.model';
@Injectable({
providedIn: 'root'
})
export class DataService {
apiUrl = 'myurl is in here but i cannot show'
constructor(private _http: HttpClient) { }
getUsers(){
return this._http.get<User[]>(this.apiUrl);
}
}
用户模型看起来像
export class User {
alertId: any;
itemId: string;
title: string;
description: string;
categoryId: any;
riskId: any;
sourceId: any;
startDate: any;
endDate: any;
link: string;
countryId: any;
countries: string;
keywordMatches: string;
keywordsMatched: 0;
createdDate: any;
createdBy: any;
isDeleted: true;
deletedDate: any;
deletedBy: any;
latitude: 0;
longitude: 0;
notes: string;
customerId: any;
formattedAddress: any;
firstname: any;
surname: any;
email: string;
phone: string;
smsEnabled: true;
customerName: string;
homeCountryId: any;
travellerTagId: 0;
}
这个 ts 组件使用它
import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/Models/user.model';
import { DataService } from 'src/app/Services/data.service';
@Component({
selector: 'app-side-nav-alerts',
templateUrl: './side-nav-alerts.component.html',
styleUrls: ['./side-nav-alerts.component.css']
})
export class SideNavAlertsComponent implements OnInit {
users$: User[];
constructor( private dataService : DataService) { }
ngOnInit(){
return this.dataService.getUsers()
.subscribe(data => this.users$ = data)
}
}
HTML
<div *ngFor = 'let user of users$' style="text-align: center;">
<h2>{{user.name}}</h2>
</div>
关于如何使用它来循环的任何想法?我基本上只是想遍历它并显示从 api 收集的信息我知道也许我需要将它转换为另一种数据类型,但我不确定如何执行此操作。
解决方案
你应该试试:
ngOnInit(){
this.users$ = this.dataService.getUsers()
}
代替
ngOnInit(){
return this.dataService.getUsers()
.subscribe(data => this.users$ = data)
}
由于数据是实际数据而不是Subscription
相应的数据。Observable
. 顺便说一句,您没有理由ngOnInit
有退货声明。
转动
users$: User[];
进入
users$: Observable<User[]>;
在您的 html 中,您需要像这样使用异步管道:
*ngFor = 'let user of (users$ | async)' style="text-align: center;"
推荐阅读
- angular - 角库。使用 ng-packagr 的模块编译顺序
- sql - 如何计算访问的每一行之间的经过时间
- swift - Swift 5:- 找不到应用 ID。将带有您的应用程序 ID 的字符串值添加到 Info.plist 或调用 [FBSDKSettings setAppID:]
- github - 从 CLI / Git Bash 登录 Github 的最佳方式
- c# - 计算角度最近的捕捉点
- firebase - 如何从 Firebase 集合中的多个文档中获取数据
- javascript - 扩展文件夹中的文件更改时自动重新加载 chrome 扩展
- flutter - 如何创建一个可以正确访问android原生AudioManager的flutter插件
- elasticsearch - 无法访问 elasticsearch apm 端点
- multithreading - Thread::Queue 如何在线程之间平均分配作业