RxJS 5 - websocket 数组消息
RxJS 5 - websocket array messages
我通过 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;
})
查看类似答案:
我通过 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;
})
查看类似答案: