WillD
WillD

Reputation: 6552

How to access properties of object supplied by snapshotChanges() in angularfire2?

I am pretty new to Angular and Firebase so there might be a very simple solution to this.

I am trying to use Ionic Angular and Firebase to create small web app.

I have a the following function in a service ("DataService") :

constructor(private db: AngularFireDatabase) {}
getSessions(uid: string) {
    return this.db.list(`/sessions/${uid}/`).snapshotChanges(); 
}

In an ionic page ts file I have the following:

export class DashboardPage {

  ...

  sessionList: Observable<any[]>;

  constructor(... private data: DataService ...) {
  }

  ionViewWillLoad() {
      this.sessionList = this.data.getSessions(this.authenticatedUser.uid);     
    })
  }

Then in my template html file for DashboadPage I want to have this:

<ion-list>
    <ion-item *ngFor="let session of sessionList | async" text-wrap>
        {{ session.payload.name }}
    </ion-item>
</ion-list>    

Now, the problem here is that the {{ session.payload.name }} expression doesn't work.

Interestingly I can do {{ session | json }} and {{ session.payload | json }} and they both will render text on the page. But when I try to drill down one more layer and add the property for the 'name' it just shows up as blank. Here's what the first list item contains when it has {{ session | json }}:

{
  "payload": {
    "name": "One",
    "notes": {
      "-L3o08afJDL025aTYHSd": {
        "content": "The first thing in my session\n",
        "systemTime": 1516996172239
      },
      "-L3o09m9n9ewPE7kOZKv": {
        "content": "The 2nd thing in my session \n",
        "systemTime": 1516996177071
      },
      "-L3o0BlH5MbgGB-N54H5": {
        "content": "The third thing in session \"One\"\n",
        "systemTime": 1516996185207
      }
    },
    "ownerUid": "cT6gbEZBalPNUOz5bwqs6l5rH5t2",
    "systemTime": 1516996163072
  },
  "type": "value",
  "prevKey": null,
  "key": "-L3o06MSYcSS2dXJBMKO"
}

So the puzzle here is why can't I access the content from the "name" key (or any other key from that level).

Thanks!

Upvotes: 0

Views: 980

Answers (1)

WillD
WillD

Reputation: 6552

User 'Hareesh' supplied correct answer in a comment:

use the .val() method on the snapshot. For example:

{{ session.payload.val().name }}

With documentation here:

https://firebase.google.com/docs/database/web/read-and-write#listen_for_value_events

Upvotes: 4

Related Questions