I'm building a chat with Socket.io
.
How to add a new message to an array list when it's async pipe loaded? Is it overcomplicated?
Should I use subscribe
instead because is it easier?
subscribe
<ul >
<li *ngFor="let message of output">
<p>
<b>{{ message.userName }}</b>
</p>
{{ message.text }}
</li>
</ul>
output: any[] = [];
this.chatService.listen('message-broadcast')
.subscribe((result) =>{
this.output.push(result);
});
async pipe
<ul >
<ng-container *ngIf="(output$ | async) as output">
<li *ngFor="let message of output">
<p>
<b>{{ message.userName }}</b>
</p>
{{ message.text }}
</li>
</ng-container>
</ul>
output$!: Observable<any>;
//How to add a new message to an array list when it's async pipe loaded?
this.output$ = this.chatService.listen('message-broadcast');
this.chatService.listen
: listen for the new message event (socket.io). It returns me JSON
like below:
{
userName: "username1",
text: "Text Typed by User"
}
CodePudding user response:
You can use scan
to accumulate all messages into an array:
Component:
public messages$ = this.chatService.listen('message-broadcast').pipe(
scan((all, message) => all.concat(message), [])
);
Template:
<ul class="chat-messages-show-list">
<li *ngFor="let message of messages$ | async">
<p>
<b>{{ message.userName }}</b>
</p>
{{ message.text }}
</li>
</ul>