【发布时间】:2018-12-25 18:12:48
【问题描述】:
目前,我正在调用数据库以提取特定用户的所有对话。之后,我循环浏览这些对话,并从每个对话中提取元数据,例如消息文本、消息发送者等。
我为每个对象及其元数据创建一个对象,然后将其全部存储在一个数组中——在我的例子中是this.recentChats。
this.af.getObservable(`userChats/${this.userID}/`).pipe(
// we map the array of conversations to an array of the (before inner) observables
map(recentConversations =>
recentConversations.map(conversation =>
this.af.getObservableSortByVar(`allChats/${conversation.conversationID}/`, 'lastUpdate'))),
// combine the observables. will emit a new value of ALL conversation data when one of the conversations changes
switchMap(recentConversations => combineLatest(recentConversations)),
// map each conversation to the conversation object
map(conversations =>
conversations.map(conversationData => {
let userKey, lastMessage, lastMessageText, lastMessageSender, lastMessageDate;
for (let i = 0; conversationData.length > i; i++) {
switch (conversationData[i].key) {
case 'messages': {
lastMessage = (conversationData[i][Object.keys(conversationData[i])[Object.keys(conversationData[i]).length - 1]]);
lastMessageText = lastMessage.message;
lastMessageSender = lastMessage.sender;
lastMessageDate = lastMessage.date;
}
case 'users': {
userKey = conversationData[i].userKey;
}
}
}
return this.createConversationObject('username', userKey, lastMessageSender, lastMessageText, lastMessageDate);
}))
).subscribe(recentChats => this.recentChats = recentChats);
但是,在调用return this.createConversationObject('username', ...) 的那一行,我一直在努力分配从数据库中获取的用户的实际用户名。
基本上,我使用userKey 局部变量,它是从上面的 switch-case 代码中获得的,以便尝试执行以下操作:
let tempUsername;
this.af.getUserName(userKey).then((username) => {
tempUsername = username;
}
然后在return语句中传递tempUsername。但是,我一直在努力等待结果 - 为了在调用 return 之前获取用户名。
有没有人有任何建议我怎样才能正确地达到预期的结果?
【问题讨论】:
-
this.af.getObservableSortByVar()是否也返回Observable?
标签: angular firebase-realtime-database promise observable angularfire2