【发布时间】:2023-03-18 07:08:01
【问题描述】:
我在 Angular 4 项目中使用 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');
}
}
【问题讨论】:
标签: angular websocket rxjs rxjs5