【发布时间】:2021-11-23 00:52:08
【问题描述】:
我正在与Socket.io 建立聊天。
加载异步管道时如何将新消息添加到数组列表?是否过于复杂?
我应该改用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);
});
异步管道
<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:监听新消息事件(socket.io)。它返回给我JSON,如下所示:
{
userName: "username1",
text: "Text Typed by User"
}
【问题讨论】:
-
那么消息广播每次发送一条消息时返回一条消息,而不是消息列表?
-
使用behaviorsubject并管道你的chatService.listen服务