Estoy creando un chat con Socket.io . ¿Cómo agregar un nuevo mensaje a una lista de matriz cuando está cargada una tubería asíncrona? ¿Es demasiado complicado? ¿Debería usar subscribe en su lugar porque es más fácil?
suscribir
<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); });tubería asíncrona
<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 : escuche el nuevo evento de mensaje (socket.io). Me devuelve JSON como a continuación:
{ userName: "username1", text: "Text Typed by User" }Puede usar el scan para acumular todos los mensajes en una matriz:
Componente :
public messages$ = this.chatService.listen('message-broadcast').pipe( scan((all, message) => all.concat(message), []) );Plantilla :
<ul class="chat-messages-show-list"> <li *ngFor="let message of messages$ | async"> <p> <b>{{ message.userName }}</b> </p> {{ message.text }} </li> </ul>