Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
How to add a new message to an array list when it's async pipe loaded?

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 class="chat-messages-show-list">
    <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 class="chat-messages-show-list">
  <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"
} 
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!