有没有办法知道rxjs websocket是否打开

有没有办法知道rxjs websocket是否打开

问题描述:

我在一个角度4的项目中使用RxJS。有没有办法知道rxjs websocket是否打开

我试图启动一个WebSocket,特别是要知道什么时候这个打开。

我目前使用RxJS(v5)的WebSocket。 https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts

我注意到WebSocketSubjectConfig中有一个openObserver,但我找不到如何创建Observer。我从几个小时就锁定了它。

这里是我的代码的摘录到目前为止:

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

观察者可以是至少部分地实现了Observer接口的任何对象。见https://github.com/ReactiveX/rxjs/blob/master/src/Observer.ts

这意味着你可以例如编写自定义类:

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

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

最终,在WebSocketSubject情况下,你可以使它更加简单,使对象只有next方法,因为openObserver期望和目标与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'); 
    } 
    } 
}); 
+0

非常感谢!你让我今天一整天都感觉很好 :) – millerf