[英]Angular 4 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays
Here is the code below: 这是下面的代码:
by selecting match geting id in routing, then taking this id from URL 通过选择匹配的路由中获取ID,然后从网址中获取此ID
export class MatchComponent implements OnInit {
_postArrayMatch: match[];
constructor(public router:Router, private matchService: MatchService,
private route: ActivatedRoute) {}
ngOnInit(){
this.getMatchId();
}
getMatchId() :void {
this.route.params.forEach((params: Params)=> {
let id = +params['id'];
this.matchService.getMatch(id).subscribe(
resultArray => this._postArrayMatch = resultArray,
error => console.log("Error ::" + error))
})
}
just basic interpolation by doing ngFor loop 通过ngFor循环进行基本插值
<div *ngFor="let post of _postArrayMatch">
<p>{{post.team1.name}}</p>
</div>
passing the dynamic id 传递动态ID
getMatch(id:number): Observable<match[]>{
return this.http.get<match[]>(`http://localhost:3000/match/${id}`)
}
interface 接口
export interface match{
team1:{
name:string,
id:number
}
team2:{
name:string,
id:number
}
}
Thats seems the easiest way i could find on how to get the data from objects. 那就是我找到如何从对象中获取数据的最简单方法。
<div *ngFor="let post of objectKeys(_postArrayMatch.team1)">
<div> Team1: {{ _postArrayMatch.team1[post]}}</div>
</div>
component.ts component.ts
objectKeys = Object.keys;
Try something like this where you create the object in your response 尝试类似这样的操作,在响应中创建对象
component.ts component.ts
export class MatchComponent implements OnInit {
_postArrayMatch: match[];
newArr: Array<Object> = [];
constructor(public router:Router, private matchService: MatchService,
private route: ActivatedRoute) {}
ngOnInit(){
this.getMatchId();
}
getMatchId() :void {
this.route.params.forEach((params: Params)=> {
let id = +params['id'];
this.matchService.getMatch(id).subscribe(
resultArray => {
this._postArrayMatch = resultArray;
const keys = Object.keys(this._postArrayMatch) // new stuff starts here
for(let i = 0; i < keys.length; i++) {
newArr.push(this._postArrayMatch[keys[i]]);
newArr[i]['team'] = keys[i];
}
},
error => console.log("Error ::" + error))
})
}
And then you can access ALL of your sub objects in your html 然后,您可以访问html中的所有子对象
Component.html Component.html
<div *ngFor="let post of newArr">
<p> {{post.team}}: {{post.name}}</p>
</div>
Currently, with what you have you are hard coding for team 1, and if you want to do that then you shouldn't be using the *ngFor
目前,对于您所拥有的,您正在为团队1进行硬编码,如果您想这样做,那么您不应该使用
*ngFor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.