1

I receive messages via a websocket connection in this format :

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

based on some examples I found on the web here is my code:

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
        });

What I want to achieve is to split the message (array) in objects and when I subscribe I want to receive those objects and not the array of objects.

1 Answer 1

1

Most easily just use concatAll() or mergeAll() that when used with arrays in RxJS 5 reemits all its items.

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();

I didn't test it but I think you could also use shorter variant:

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;
    })

See similar answers:

Sign up to request clarification or add additional context in comments.

1 Comment

I've tested the concatMap example and works like a charm. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.