In my Ionic / Angular app, a Conversation object contains an array of Message objects.
I am able to add Conversations , no problem using the below code. When I console.log this.conversations , all of the Conversations are displayed.
private _conversations = new BehaviorSubject<Conversation[]>([]);
get conversations() {
return this._conversations.asObservable();
}
addConversation(mechanicId: string, message: string) {
let generatedId;
const newConversation = new Conversation(
Math.random().toString(),
[new Message(
Math.random().toString(),
message,
)]
);
return this.http.post<{ name: string }>(
'myUrl/conversations.json',
{ ...newConversation, id: null }
).pipe(
switchMap(resData => {
generatedId = resData.name;
console.log('My Conversations', this.conversations);
return this.conversations;
}),
take(1),
tap(conversations => {
newConversation.id = generatedId;
this._conversations.next(conversations.concat(newConversation));
})
);
}
However, when I try to update a Conversation (i.e. add a new Message to it), when I console.log this.conversations , I am only getting back the Conversation which I am updating:
addMessageToConversation(conversationId: string, message: string) {
let updatedConversations: Conversation[];
return this.conversations.pipe(
take(1),
switchMap((conversationToUpdate: any) => {
conversationToUpdate.messages.push(
new Message(
Math.random().toString(),
message,
this.authService.userId,
new Date(Date.now())
)
);
console.log('Conversations after adding new message', this.conversations);
// This only shows the Conversation I am looking @ currently. I want it to have all the latest Conversations & Messages, not just this one
return this.http.put(
`myUrl/conversations/${conversationId}.json`,
{ ...conversationToUpdate, id: null }
);
}), tap(() => {
// this._conversations.next(updatedConversations); // dont't think this is doing what I want it to
})
);
}
I want to get back all of the Conversations so that _conversations always contains the latest Conversations .
Can someone please tell me how I can ensure _conversations always contains all Conversations , rather than just the one who’s ID is passed into addMessageToConversation() ?
So if I add a new Conversation, it shows all Conversations in the console. But if I add a new Message to a Conversation, it only shows that Conversation in the console, while I want it to show all Conversations.