Is there a way to find out if rxjs websocket is open

I am using RxJS in angular 4 project.

I am trying to initiate a website and especially know when it opens.

I am currently using WebSocket from RxJS (v5). https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts

I noticed that there is an openObserver in the WebSocketSubjectConfig, but I cannot find how to create the Observer. I've been locked on it since a few hours.

Here is a snippet of my code:

import { Injectable } from '@angular/core';
import { webSocket} from 'rxjs/observable/dom/webSocket';
import { WebSocketSubject, WebSocketSubjectConfig} from 'rxjs/observable/dom/WebSocketSubject';

@Injectable()
export class MzkWebsocketJsonRpcService {
    subject: WebSocketSubject<any>;
    jsonRpcId: number;

    constructor() {

        this.subject = webSocket('ws://localhost:12345');
        this.subject.openObserver =
            /// Find a way to create the openObserver


        this.subject.subscribe(
            this.onMessage,
            this.onError,
            this.onClose,
        );
        console.log('Socket connected');
        this.jsonRpcId = 1;
    }

    public send(method: string, params: any[]) {

        let jsonFrame: any = {id: this.jsonRpcId, 'json-rpc': '2.0', method: method};

        if (params) {
            jsonFrame['params'] = params;
        }
        this.subject.next(JSON.stringify(jsonFrame));
        this.jsonRpcId ++;
    }

    onMessage(data: string) {
        console.log('Websocket message: ', data);
    }

    onError(data: string) {
        console.log('Websocket error:', data);
    }

    onClose() {
        console.log('Websocket closing');
    }
}

      

+3


source to share


1 answer


An observer can be any object that at least partially implements an interface Observer

. See https://github.com/ReactiveX/rxjs/blob/master/src/Observer.ts

This means that you can, for example, write your own class:

MyObserver implements Observer {
  next(value: any): void {
    ...
  }
  complete(): void {
    ...
  }
}

let socket = new WebSocketSubject({
  url: 'ws://localhost:8081',
  openObserver: new MyObserver()
});

      



In the end, in case WebSocketSubject

you can make it even simpler and create an object using only a method next

, because it openObserver

expects an object with the interface NextObserver

https://github.com/ReactiveX/rxjs/blob/master/src/Observer.ts#L1 ...

let socket = new WebSocketSubject({
  url: 'ws://localhost:8081',
  openObserver: {
    next: (val: any) => {
      console.log('opened');
    }
  }
});

      

+3


source







All Articles