[英]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: 我正在构建一个由此Firebase数据库结构支持的简单聊天应用程序:
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. 我正在使用Angular2和AngularFire2生成HTML。 I have a simple list of messages from the Firebase Database in my controller: 我在控制器中有一个来自Firebase数据库的简单消息列表:
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. 我想检测每条消息中的某些条件,并将其转换为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: 我的HTML模板:
<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: 在Firebase JavaScript SDK中,这类似于:
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? 我应该如何在AngularFire2中进行此类客户端丰富?
Not sure how things work in JSSDK, but when you subscribe (with async
pipe) to FirebaseListObservable
you are disconnected from Firebase (upstrem); 不确定JSSDK中的工作方式如何,但是当您(使用async
管道)订阅FirebaseListObservable
您将与Firebase断开连接(upstrem)。 you will still get updates (downstrem). 您仍将获得更新(downstrem)。 So you can just chain map()
to the observable, and add property in the client: 因此,您可以将map()
到可观察对象,然后在客户端中添加属性:
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. 如果您在服务器端使用第3条记录更新数据,则模板应更新。 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: 但是,您不能在客户端上的this.messages
添加新消息,必须重新创建引用并以这种方式更新服务器:
af.database.list('messages').push({
name: "new",
text: "Now I'm sad :-("
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.