Reputation: 65
I make a request to firestore to get a user's chats and it returns an observable array of objects with this shape
[...,
{
key: '83hed87djhe09',
participants: ['owner_43', 'visitor_69']
},
...]
This displays a list of all user's chats in the UI, however I'd like to search for chats by user name. In order to do that, I'd have to make a http request to a backend server for the user name of each participant and replace that in the participants thread to make it searchable on type.
So 'owner_43' would become 'John Doe' for example.
Problem I'm experiencing is that I get an array of observables for the participant names rather than an array of strings.
Here's my code
this.chat$ = this.chatSvc.getUserChats(this.userUID).pipe(
map((chats: any) => {
return chats.map((chat: any) => {
return {
key: chat.key,
participants: chat.participants.map((participant: any) => {
return this.userSvc.getUserFromString(participant);
})
}
})
})
);
Here's the getUserFromString function:
getUserFromString(stringId){
let splitValue = stringId.split("_");
let accountType = splitValue[0];
let id = splitValue[1];
if (accountType === 'owner') {
return this.ownerSvc.getOwner(id);
}
else if (accountType === 'visitor') {
return this.visitorSvc.getVisitor(id);
}
}
Get owner function simply returns:
return this.http.get(owner_url + id);
Finally the result is unwrapped in the view using the angular async pipe
<ul><li *ngFor="let msg of chat$|async">{{msg.key}}</li></ul>
What am I doing wrong?
Upvotes: 1
Views: 550
Reputation: 6424
Assuming your Chat
looks like this:
/**
* Type parameter is being used
* due to participants initially being of type string[]
* and ultimately of type User[]
*/
class Chat<T> {
key: string;
participants: T[]
}
Consider the following implementation:
this.chat$: Observable<Chat<User>[]> = this.chatSvc.getUserChats(this.userUID).pipe(
mergeAll(),
mergeMap(({ key, participants }: Chat<string>) => {
return forkJoin(participants.map(this.userSvc.getUserFromString)).pipe(
map(participants => ({ key, participants }))
)
}),
toArray()
)
Explanation (Simplified):
this.chat$ = this.chatSvc.getUserChats(this.userUID).pipe(
/**
* flattens Observable<Chat[]> into a stream
* of Observable<Chat> so we can handle single Chat at a time
*/
mergeAll(),
/**
* transform each Chat into an
* Observable containing a new value
*/
mergeMap(({ key, participants }: Chat) => {
/**
* transform participants (String[]) into an array of Observables
* (Observable<User>[])
*/
const participants$ = participants.map(this.userSvc.getUserFromString)
/**
* wait for all Observables to complete using forkJoin
* then return new Chat using map
*/
return forkJoin(participants).pipe(
map(participants => ({ key: key, participants: participants }))
)
}),
toArray() // <= transform stream back into array (Observable<Chat[]>)
)
Upvotes: 1