1

I have some JSON data in Firebase and I'm trying to loop through the data with *ngFor in Angular v5.

The object looks like this:

{
    "events": [
        {
            "Event-time": "09:30",
            "Event-name": "Morning Session",
            "Location": "Alexander Room",
            "Speaker-image": "https://z4e3q7e996-flywheel.netdna-ssl.com/wp-content/uploads/2017/07/TeamPhotosIan.png",
            "Speaker-name": "Ian Broom",
            "Speaker-title": "CEO & Founder"
        },
        {
            "Event-time": "11:30",
            "Event-name": "Morning Session II",
            "Location": "Coffee Room",
            "Speaker-image": "https://z4e3q7e996-flywheel.netdna-ssl.com/wp-content/uploads/2012/07/TeamPhotosben.png",
            "Speaker-name": "Ben Wynne-Simmons",
            "Speaker-title": "Head of Growth & Marketing"
        }
   ]
}

This is my events-list.component:

export class EventsListComponent implements OnInit {
    eventsObservable: Observable<any[]>;

    constructor(private db: AngularFireDatabase) { }

    ngOnInit() {
        this.eventsObservable = this.getEvents('/events');
    }

    getEvents(listPath): Observable<any[]> {
        return this.db.list(listPath).valueChanges();
    }
}

I'm trying to loop through like so:

<ul>
    <li *ngFor="let event of eventsObservable | async">
        <p>{{event.Event-name}}</p>
    </li>
</ul>

What gets printed out is NaN.

I don't know how to access and display the data.

Please help! Thanks!

2 Answers 2

1

The problem is to access a field that contains the sign -.

It is interpreted as a mathematical substraction (and since neither event.Event nor name is a number, event.Event - name gives NaN (NotANumber).

To access such a field with special characters in name, you have to use the brackets notation :

<p>{{event["Event-name"]}}</p>

Also, as other answer tells, you have to iterate on your array directly. It's not very clear to me how you get your observable in your answer. If you get an Observable out of the big object, then you should .map your observable to its events field.

This will give you another observable, and you should iterate on the latter.

Sign up to request clarification or add additional context in comments.

3 Comments

Of course!!! How could I not see that? Thank you so very much, it's working perfectly! To clarify, the eventsObservable stays as is.
And thank you too for clarification, I'm not a Firebase user . Glad it works now!
I'm open to suggestions for improving my code. Thanks a lot for your help!
0

You need to access events which is an array inside eventsObservable object

<div *ngFor="let event of eventsObservable.events | async">
        <p>{{event.Event-name}}</p>
 </div>

1 Comment

Thank for your answer, but unfortunately that's not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.