Let me share with you how I initialize my variable threads:
threads: Observable<{ [key: string]: Thread }>;
Here is the code snippet for initializing my variable threads :
this.threads = messageService.messages
.map((messages: Message[]) => {
const threads: { [key: string]: Thread } = {};
messages.map((message: Message) => {
threads[message.thread.id] = threads[message.thread.id] ||
message.thread;
const messagesThread: Thread = threads[message.thread.id];
if (!messagesThread.lastMessage ||
messagesThread.lastMessage.date < message.date) {
messagesThread.lastMessage = message;
}
});
return threads;
});
I have a requirement to add a new thread to the existing variable threads :
const newThread: Thread = new Thread(objMessage.id, objmessage.participants);
I attempted the following approaches:
threads = Observable.of([newThread]);
And also this :
this.threads.subscribe((thread: Thread) => {
threads.next(newThread);
});
Unfortunately, none of these solutions seem to work due to incorrect type assignment.
////////////////////////////////////////////////////////////////////////////
EDIT :
////////////////////////////////////////////////////////////////////////////
By changing my thread variable to BehaviorSubject:
threads: BehaviorSubject<{[key: string]: Thread }> = BehaviorSubject.create();
I had to modify the initialization in the following way :
this.messageService.messages.map((messages: Message[]) => {
const threads: { [key: string]: Thread } = {};
messages.map((message: Message) => {
threads[message.thread.id] = threads[message.thread.id] ||
message.thread;
const messagesThread: Thread = threads[message.thread.id];
if (!messagesThread.lastMessage ||
messagesThread.lastMessage.date < message.date) {
messagesThread.lastMessage = message;
}
});
return threads;
}).subscribe(threads => {
this.threads.next(threads);
});
Additionally, I added :
addThread(newThread: Thread): void {
this.threadService.newThreads.push(newThread);
this.threadService.newThreadsId.push(newThread.id);
this.threadService.orderedThreads.next(this.threadService.newThreads);
let threads = this.threadService.threads.value;
this.threadService.threads.next(threads);
}
After executing the above logic, an error occurred :
Cannot set property 'flo' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot set property 'tRev' of undefined
'flo' refers to the id of my Thread :
this.addNewMessageNewThread({
"id": "flo",
"author": "Flo Peron",
"body": "COUUUUCOU",
"title": "Groupe 158"
});