Reputation: 509
As i'm new to angular, I couldn't able to show data on my component.html page. I get the Observable but not able to show it on page. it shows ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'Prabu'. NgFor only supports binding to Iterables such as Arrays. error on the console. Please help. Thanks in advance.
Angular:
import { AngularFireDatabase } from '@angular/fire/database';
export class AppComponent {
author$;
constructor(db: AngularFireDatabase) {
this.author$ = db.object('/authors/1').valueChanges();
this.author$.subscribe(console.log);
}
}
HTML:
<ul class="list-group mt-3">
<li class="list-group-item" *ngFor="let author of author$ | async">{{author}}</li>
</ul>
Database:
Response on Console:
Upvotes: 0
Views: 125
Reputation: 8660
The issue here is that you are receiving an object and trying to iterate over it. If you want to iterate over the key-value pairs in an object, you will need to first convert it into an array. You can do this using the KeyValuePipe.
<ul class="list-group mt-3">
<li class="list-group-item" *ngFor="let author of author$ | async | keyvalue">{{author.key}} - {{author.value}}</li>
</ul>
If you want to simply display the name
in the template, you can do so like below
<div>
<!-- To display another item in the object, simply replace name with the required key, eg. (author$ | async)?.students -->
{{(author$ | async)?.name}}
</div>
Your component will now look like this
import { Observable } from 'rxjs';
export class AppComponent {
author$: Observable<any>;
constructor(private db: AngularFireDatabase) { }
ngOnInit() {
this.author$ = this.db.object('/authors/1').valueChanges();
}
}
I have moved the logic to the ngOnInit
function as that is the best practice rather than doing it in the contructor
(Source: docs).
Here is a working example on StackBlitz.
Note: The
KeyValuePipe
will only work with Angular version 6+
Upvotes: 1
Reputation: 2359
*ngFor works on array not object. You are getting a single object of Prabu.In constructor use below line to get all authors.
db.object('/authors').valueChanges().subscribe((authors)=>{
this.author$ = authors.
);
In template
<li class="list-group-item" *ngFor="let author of author$ | async">{{author.name}}</li>
Upvotes: 0