How do I add client-side attributes to items in a FirebaseListObservable?

I'm building a simple chat app backed by this Firebase Database structure:

messages: {
  "-KTjL_oLrKOboa2su2zk": {
    name: "puf",
    text: "Look I'm smiling :-)"
  },
  "-KTjNfaNem752ChFBcnC": {
    name: "puf",
    text: "And now I'm not smiling"
  }
}

I'm using Angular2 and AngularFire2 to generate the HTML. I have a simple list of messages from the Firebase Database in my controller:

export class AppComponent {
  messages: FirebaseListObservable<any[]>;
  constructor(public af: AngularFire) {
    this.messages = af.database.list('messages');
  }
}

I want to detect certain conditions in each message and translate that into an emoji in my HTML. Since this is purely display information derived from the existing content, I don't want to store it in the database.

My HTML template:

<li class="text" *ngFor="let message of messages | async">
  {{message.name}} {{message.emoji}}: {{message.text}}
</li>

In the Firebase JavaScript SDK, this would be akin to:

ref.on('child_added', function(snapshot) {
  var message = snapshot.val();
  if (message.text.indexOf(':-)') >= 0) {
    message.emoji = '????';
  }
  addMessageToHTML(message);
});

How should I do such client-side enrichment in AngularFire2?

Answers:

Answer

Not sure how things work in JSSDK, but when you subscribe (with async pipe) to FirebaseListObservable you are disconnected from Firebase (upstrem); you will still get updates (downstrem). So you can just chain map() to the observable, and add property in the client:

import 'rxjs/add/operator/map'

export class AppComponent {
  messages: FirebaseListObservable<any[]>;
  constructor(public af: AngularFire) {
    this.messages = af.database.list('messages')
      .map(messages => messages.map(message => {
        if (message.text.indexOf(':-)') >= 0) {
          message.emoji = '????';
        }
        return message;
      }))
  }
}

UPDATE: working example

If you update data with 3rd record on the server side, template should update. You can't however add new message to the this.messages on the client, you have to recreate reference and update the server that way:

    af.database.list('messages').push({
      name: "new",
      text: "Now I'm sad :-("
      }
    }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.