我通过 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/