我正在尝试在AngularFire2应用中列出用户对话,其结构如下:
聊天
"chat1": {
title: "First chat",
lastMessage: "Hello world",
members: {
"user1": true,
"user2": true,
}
}
用户
"user1": {
name: "Ben",
surname: "Bennsay"
}
"user2": {...}
我正在尝试以一种方式映射和列出聊天,以便我可以轻松地显示聊天参与者名称在最后一条消息之后。
问题1:此示例与官方推荐略有不同,但我觉得它仍然有效且可扩展。我是对的吗?
问题2:如何在我的聊天列表中实际加入成员和用户以获得users
数组?
这是我到目前为止所拥有的。
// retrieve chats "user1" participates in
this.afChatsRef = this.af.database.list(this.datastore(), {
query: {
orderByChild: "/members/user1", // by user id in members
equalTo: true,
}
}).map(chats => {
chats.map(chat => {
// HMMM? WHAT TO DO HERE ?
});
return chats;
});
提前谢谢。
UPDATE我也试过以下,这似乎不太正确(我无法访问用户属性)。
this.af.database.list(this.datastore()).map(chats => {
chats.map(chat => {
// chat.users = [];
for (var key in chat.members) {
this.af.database.object("/users/" + key).subscribe(user => {
chat.members[key] = user;
});
}
return chat;
});
console.log(chats);
return chats;
});
答案 0 :(得分:0)
您想要返回嵌套地图并获取其中的用户。像这样的东西;
// retrieve chats "user1" participates in
this.afChatsRef = this.af.database.list(...).map(chats => {
// Note the return!
return chats.map(chat => {
// Avoid side effects by storing members separate from the keys
chat.memberData = {};
// Iterate keys and download members
Object.keys(chat.members||{}).forEach(uid => {
// `users` represents a service to cache and load users on demand
chat.memberData[uid] = users.load(uid);
});
});
return chats;
});
这是使用缓存创建用户服务的好方法:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class UserProvider {
db: AngularFireDatabase;
users: Map<String, Observable<User>>;
constructor(db: AngularFireDatabase) {
this.db = db;
this.users = new Map();
}
load(userid:string) : Observable<User> {
if( !this.users.has(userid) ) {
this.users.set(userid, this.db.object(`members/${userid}`).valueChanges());
}
return this.users.get(userid);
}
}
export interface User {
name:string;
nick:string;
}
这是AngularFire2中的working example异步连接。