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

主宰稳场 提交于 2019-12-04 04:50:06

问题


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?


回答1:


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 :-("
      }
    }


来源:https://stackoverflow.com/questions/39984247/how-do-i-add-client-side-attributes-to-items-in-a-firebaselistobservable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!