In my Ionic 5 / Angular app, I am trying to update a Conversation object within the below Conversation array:
private _conversations = new BehaviorSubject<Conversation[]>([
new Conversation(
'conversation1',
'user3',
'user1',
[
new Message('message1', 'Test message', 'user3', new Date(2018, 0O5, 0O5, 17, 23, 42, 11)),
new Message('message2', 'Another message', 'user1', new Date(2018, 0O6, 0O5, 17, 23, 42, 11))
]),
new Conversation(
'conversation2',
'user4',
'user2',
[
new Message('message3', 'my message', 'user4', new Date(2018, 0O7, 0O7, 17, 23, 42, 11)),
new Message('message4', 'more messages', 'user2', new Date(2018, 0O7, 0O7, 17, 23, 42, 11)),
])
]);
Here are the Conversation & Message models I'm using:
export class Conversation {
constructor(
public id: string,
public userId: string,
public mechanicId: string,
public messages: Message[]
) { }
}
export class Message {
constructor(
public id: string,
public text: string,
public userId: string,
public timestamp: Date
) { }
}
I'm able to add to the array using these methods below:
addConversation(mechanicId: string, message: string) {
const newConversation = new Conversation(
Math.random().toString(),
this.authService.userId,
mechanicId,
[this.createMessage(message)]
);
return this.conversations.pipe(
take(1),
delay(1000),
tap(conversations => {
this._conversations.next(conversations.concat(newConversation));
}));
}
private createMessage(message: string): Message {
return {
id: Math.random().toString(),
text: message,
userId: this.authService.userId,
timestamp: new Date(Date.now())
};
}
But I'm unable to update a Conversation (i.e. Add a new Message object to an existing Conversation object).
Here is my latest attempt:
addToConversation(id: string, mechanicId: string, message: string) {
const conversation = this.getConversation(id);
if (conversation) {
conversation.messages.push(
this.createMessage(message)
);
}
}
This doesn't work however, as I get the following error message on conversation.messages.push:
Property 'messages' does not exist on type Observable<{ id: string, userId: string, mechanicId: string, messages: Message[]; }>
Also, here is getConversation():
getConversation(id: string) {
return this.conversations.pipe(
take(1),
map(conversations => {
return { ...conversations.find(conversation => conversation.id === id) };
}));
}
get conversations() {
return this._conversations.asObservable();
}
getConversation(id)function?this.conversationsvariable is defined.