【问题标题】:RxJS 5 - websocket array messagesRxJS 5 - websocket 数组消息
【发布时间】:2017-06-27 21:54:51
【问题描述】:

我通过 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
        });

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

【问题讨论】:

    标签: javascript typescript websocket rxjs rxjs5


    【解决方案1】:

    最容易使用 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;
        })
    

    查看类似答案:

    【讨论】:

    • 我已经测试了 concatMap 示例并且工作起来就像一个魅力。谢谢
    猜你喜欢
    • 2022-01-23
    • 2021-05-18
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2018-02-01
    • 1970-01-01
    相关资源
    最近更新 更多