【问题标题】:How to add a new message to an array list when it's async pipe loaded?加载异步管道时如何向数组列表添加新消息?
【发布时间】: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服务

标签: angular rxjs


【解决方案1】:

您可以使用scan 将所有消息累积到一个数组中:

组件

public messages$ = this.chatService.listen('message-broadcast').pipe(
    scan((all, message) => all.concat(message), [])
);

模板

<ul class="chat-messages-show-list">
  <li *ngFor="let message of messages$ | async">
    <p>
      <b>{{ message.userName }}</b>
    </p>
    {{ message.text }}
  </li>
</ul>

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 2019-03-07
    • 2013-05-17
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2019-08-06
    相关资源
    最近更新 更多