聊天 angular websocket,按顺序显示元素 [英] Chat angular websocket, display element sequencially

查看:35
本文介绍了聊天 angular websocket,按顺序显示元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与 Angular 和 socket.io 进行聊天.服务器可以在短时间内发出许多事件,前端必须一个接一个地处理每个事件.

I'm working on a chat with Angular and socket.io. Server can emit many events in a few time, front has to treat every event one after the other.

// My socket service
message: Subject<any> = new Subject<any>();
this.socket.on('messageToServer', (data) => {
  this.message.next(data);
});

// My component
this.socketService.message.subscribe(
  async (msg) => await this.display(msg)
);

async display(msg): Promise<void> {
  try {
    console.log('start speaking');
    await this.botSpeak(msg.message);
    this.displayedMessages.push(msg);
    console.log('stop speaking');
  } catch (e) {

  }
}

这是日志:

start speaking
start speaking
stop speaking
stop speaking

这是正常的,因为套接字发出了两次,但我需要在处理 2 之前等待处理 1 才能获得正确的日志:

it's normal because the socket was emitted twice, but i need to wait treatment one before treatment 2 to get this correct log :

start speaking
stop speaking
start speaking
stop speaking

选项 1:使用显示或不显示布尔值的数组.
选项 2:使用队列?怎么样?
我对做到这一点的最佳方法有点迷茫,感谢您的帮助!

Option 1 : use an array with a boolean displayed or not.
Option 2 : use a queue ? how ?
I'm a bit lost about the best way to do that, thanks for your help !

推荐答案

concatMap 是这里的解决方案,这里是示例:https://stackblitz.com/edit/angular-ivy-mdk9s7?file=src/app/app.component.ts

concatMap is the solution here, here's the sample: https://stackblitz.com/edit/angular-ivy-mdk9s7?file=src/app/app.component.ts

双击按钮并查看控制台,输出将按顺序发出.

double click on the button and look at the console, output will emit in order.

将 fromEvent 替换为您的服务返回的 observable,它将按预期工作.

replace that fromEvent with the observable returned by your service and it'll work as expected.

好吧,如果你懒得打开链接哈哈,这里是代码:

and well if you're feeling too lazy to open the link lol, here's the code:

this.socketService.message.pipe(
    concatMap(msg => from(this.display(msg))) // use from operator to convert a promise to an observable
).subscribe({
    next: _ => {}
});

这篇关于聊天 angular websocket,按顺序显示元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆