我在尝试打印所有数据库记录时遇到Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
错误。
我已使用此source从firebase获取数据。不知怎的,它不起作用。我的json文件结构是错误的还是数组的类型应该不同? 我做错了什么?
firebase(json)
{
"clients" : {
"-L4jvQwBFM0W8A928waj" : {
"id" : "124",
"lastName" : "sda421",
"name" : "412"
},
"-L4jz52GfcU4ZsJx_LX0" : {
"id" : "214",
"lastName" : "sda ",
"name" : "sad "
},
"-L4k-5xNmN4dalqFj2dB" : {
"id" : "12345678",
"lastName" : "Pafasfbin",
"name" : "fasf"
},
"-L4k-Dw5TA6FnHpWDiIq" : {
"id" : "52353235",
"lastName" : "qweqw",
"name" : "qwrqwe "
}
}
}
clients.component.ts
import { Component, OnInit } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabase } from 'angularfire2/database' ;
import { Observable } from 'rxjs';
@Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
// clients: any[];
clients: Observable<any[]>;
name: string;
lastName: string;
id: number;
constructor(public db: AngularFireDatabase) { }
ngOnInit() {
this.getData();
}
getData(){
this.clients = this.db.list('/clients').valueChanges();
console.log(this.clients);
}
}
clients.component.html
<ul>
<li *ngFor="let i of clients">
<label>name: </label> {{ i.name }}
<label>lastName: </label> {{ i.lastName }}
<label>ID: </label> {{ i.id }}
</li>
</ul>
答案 0 :(得分:0)
在Angular2 +中,
你不能通过ngFor遍历json对象,值应该是
Iterables such as Arrays
但是在你的情况下它仍然是你的目标 想要循环通过对象,你可以按照你的方式做这样的事情 响应
组件方:
objectKeys = Object.keys;
模板面:
<ul>
<li *ngFor="let key of objectKeys(clients)">
<label>name: </label> {{ clients[key].name }}
<label>lastName: </label> {{ clients[key].lastName }}
<label>ID: </label> {{ clients[key].id }}
</li>
</ul>
<强> WORKING DEMO 强>
答案 1 :(得分:0)
查看以下代码段。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
clients:any;
data=`{
"clients" : {
"-L4jvQwBFM0W8A928waj" : {
"id" : "124",
"lastName" : "sda421",
"name" : "412"
},
"-L4jz52GfcU4ZsJx_LX0" : {
"id" : "214",
"lastName" : "sda ",
"name" : "sad "
},
"-L4k-5xNmN4dalqFj2dB" : {
"id" : "12345678",
"lastName" : "Pafasfbin",
"name" : "fasf"
},
"-L4k-Dw5TA6FnHpWDiIq" : {
"id" : "52353235",
"lastName" : "qweqw",
"name" : "qwrqwe "
}
}
}`
objectKeys;
ngOnInit(){
this.objectKeys = Object.keys;
this.clients=JSON.parse(this.data).clients;
console.log(this.clients);
}
}
<ul>
<li *ngFor="let i of objectKeys(clients)">
<label>name: </label> {{ clients[i].name }}
<label>lastName: </label> {{ clients[i].lastName }}
<label>ID: </label> {{ clients[i].id }}
</li>
</ul>
<强> DEMO 强>