javascript - RxJS 5 - websocket 数组消息

标签 javascript typescript websocket rxjs rxjs5

我通过 websocket 连接接收以下格式的消息:

    [
      {
        //msg 1
      },
      {
        //msg 2
      },
      ....
    ]

根据我在网上找到的一些示例,这是我的代码:

public messages: Subject<Message> = new Subject<Message>();
//...
        this.messages = <Subject<Message>>this.wsService
            .connect(COMMUNICATION_URL)
            .map((response: MessageEvent): Message => {
                let data = JSON.parse(response.data);
                //data is an array [ {..} , {..}, ...]
                return data;
            });


        this.messages.subscribe(msg => {
            console.log(msg);
            // msg is an array of objects [ {..} , {..}, ...]
            // I want to be just the object
        });

我想要实现的是将消息(数组)拆分为对象,当我订阅时,我想接收这些对象而不是对象数组。

最佳答案

最简单的方法是使用 concatAll()mergeAll(),当与 RxJS 5 中的数组一起使用时,它们会重新发出其所有项目。

this.messages = <Subject<Message>>this.wsService
    .connect(COMMUNICATION_URL)
    .map((response: MessageEvent): Message => {
        let data = JSON.parse(response.data);
        //data is an array [ {..} , {..}, ...]
        return data;
    })
    .concatAll();

我没有测试它,但我认为你也可以使用更短的变体:

this.messages = <Subject<Message>>this.wsService
    .connect(COMMUNICATION_URL)
    .concatMap((response: MessageEvent): Message => {
        let data = JSON.parse(response.data);
        //data is an array [ {..} , {..}, ...]
        return data;
    })

查看类似答案:

关于javascript - RxJS 5 - websocket 数组消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42144330/

相关文章:

javascript - 按顺序从 Carousel 控件中添加和删除元素

javascript - 仅当我们单击窗口上的任意位置时打开菜单时才切换菜单

javascript - 隐藏表行 colspan 无法工作

javascript - 将 es5 lib 包含到模板 Web 组件中

typescript - React Native Flow、TypeScript 和 Visual Studio Code

javascript - 如何使用 angular js 正确显示 JSON 响应?

reactjs - 在 typescript 中 react 懒惰

javascript - 网络场场景中的 SignalR 连接亲和性

react-native - React Native没有连接到socket.io

c++ - 使用 Echo 客户端示例从 Qt UI 连接到 WebSocket 服务器