我试图查询集合并根据另一个查询返回更改数据结果。
我的聊天结构是这样的:
let chat = {
id: "userId1" + "userId2",
lastMessage: "",
timestamp: "",
title: ""
}
我需要拆分聊天ID,查询其中一个用户并将用户名设置为聊天标题。
我尝试这样做但是没有工作,也没有在模板上显示结果。
listChats(userId: string): Observable<any[]> {
return <Observable<any[]>>this.afs.collection(this.CHATS_COLLECTION)
.snapshotChanges()
.map((c) => {
return c
.filter((chat) => chat.payload.doc.id.startsWith(userId) || chat.payload.doc.id.endsWith(userId))
.map(c => {
const chatData = c.payload.doc.data() as Chat;
const chatId = c.payload.doc.id;
//the id here comes like "id1 + id2"
let ids: string[] = c.payload.doc.id.split(this.SEPARADOR);
//get the id
let id = ids[0];
//check in firebase the user row
return this.afs.doc("users/" + id)
.snapshotChanges()
.map((c) =>{
const data = c.payload.data() as User;
let name = data.name;
//Here I need to get the user name and set on the chat data
chatData.title = name;
return { chatId, ...chatData };
});
});
});}
ChatPage.ts:
ionViewDidLoad() {
this.chats = this.chatService.listChats(userId);
}
要在模板上显示聊天内容:
<ion-list no-line>
<button ion-item *ngFor="let chat of chats | async" (click)="onOpenChat(chat)">
<h2>{{chat.title}}</h2>
</button>
</ion-list>
答案 0 :(得分:0)
使用.valueChanges()
订阅observable。
ionViewDidLoad() {
this.chats = this.chatService.listChats(userId).valueChanges();
}
尝试这些更改
listChats(userId: string): Observable<any> {
return this.afs.collection(this.CHATS_COLLECTION)
.snapshotChanges()
.map((c) => {
return c
.filter((chat) => chat.payload.doc.id.startsWith(userId) || chat.payload.doc.id.endsWith(userId))
.map(c => {
const chatData = c.payload.doc.data() as Chat;
const chatId = c.payload.doc.id;
//the id here comes like "id1 + id2"
let ids: string[] = c.payload.doc.id.split(this.SEPARADOR);
//get the id
let id = ids[0];
//check in firebase the user row
return this.afs.doc("users/" + id)
.snapshotChanges()
.map((c) =>{
const data = c.payload.data() as User;
let name = data.name;
//Here I need to get the user name and set on the chat data
chatData.title = name;
return { chatId, ...chatData };
});
});
});}