Reputation: 315
Let me explain. Here is my HTML to display my messages like this:
<message
*ngFor="let message of thread.messages | async"
[message]="message">
</message>
My thread.messages variable is an Observable.
export class Thread {
id: string;
messages: Observable<Message[]> = new Observable<Message[]>();
}
In my addNewMessage() function, I created a Subject variable to add the new messages in:
subjectMessages: Subject<Message[]> = new Subject<Message[]>();
addNewMessage(objMessage: any) : void {
const newMessage = new Message(objMessage);
this.subjectMessages.next([newMessage]);
thread.messages = this.subjectMessages.asObservable();
}
I want to convert this subjectMessages variable to the thread.messages variable. But it does not work. My thread.messages variable contains an Observable but it does not display anything in my HTML.
However, the display of the last message works :
thread.messages.subscribe((message: Message[]) => {
[thread.lastMessage] = message;
});
I despair, do you know where my mistake would be ? Why can I view the last message, not all messages?
Upvotes: 0
Views: 777
Reputation: 160
In this case, think of what you get in a subscriber as a state. In your code you emit a single message wrapped in an array, [newMessage]
. The subscribers get these emitted values as stream. If you emit the whole state, the subscribers get access to the whole array of messages.
It doesn't seem right to use both a Subject and an Observable. I haven't tried this but perhaps if you do something like this instead:
export class Thread {
id: string;
messages: Subject<Message[]> = new Subject<Message[]>();
}
messages: Message[] = new Message[];
addNewMessage(objMessage: any) : void {
const newMessage = new Message(objMessage);
messages.push(newMessage);
thread.messages.next(messages);
}
Or perhaps a better approach would be to look at ReplaySubject
or BehaviorSubject
which can be used to get previous messages as well.
Upvotes: 1