websocket 收到消息后UI未更新

ryevplcw  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(158)

我收到一条消息,我将其记录在控制台中,该控制台记录正确,我将数据推送到阵列中,但UI未更新。

constructor(
    private cdr: ChangeDetectorRef
  ) {

  ngOnInit(): void { 
    socket.on('connect', () => {

     socket.on('recieveMessage', (msg) => {
       console.log('recievemessage is triggered')
        this.messagesArr.push(msg);
        this.cdr.markForCheck();
     })

    }) 
  }

然后我尝试删除socket.on('connect '),但它在控制台中登录了不止一次,但UI更新成功,消息在UI上正确添加了一次。
代码:

constructor(
    private cdr: ChangeDetectorRef
  ) {

  ngOnInit(): void { 
     socket.on('recieveMessage', (msg) => {
       console.log('recievemessage is triggered')
        this.messagesArr.push(msg);
        this.cdr.markForCheck();
     })
  }

有人能帮助我吗?(我在两个示例中都使用了这个.cdr.detectChanges())

kcrjzv8t

kcrjzv8t1#

为消息定义一个新的数组,将其称为示例消息并在视图中使用:

messages: any[] = [];
messagesArr: any[] = [];

ngOnInit(): void { 
     socket.on('recieveMessage', (msg) => {
       console.log('recievemessage is triggered')
        this.messages = this.messagesArr.push(msg);
        this.cdr.markForCheck();
     })
  }

HTML格式

<div *ngFor="let message of messages">.......

相关问题