@Sweg wrote:
In my Ionic / Angular app, a
Conversation
object contains an array ofMessage
objects.I am able to add
Conversations
, no problem using the below code. When Iconsole.log
this.conversations
, all of theConversations
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 newMessage
to it), when Iconsole.log
this.conversations
, I am only getting back theConversation
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 latestConversations
.Can someone please tell me how I can ensure
_conversations
always contains allConversations
, rather than just the one who’s ID is passed intoaddMessageToConversation()
?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.
Posts: 1
Participants: 1