多个订阅一个Rx.Subject

时间:2018-09-24 16:10:34

标签: angular websocket rxjs angular6 rxjs6

我尝试使用Rx.Subject创建一个可观察对象,该对象将由多个组件订阅。

我有我的WebsocketService:

export class WebsocketService {
private ws = null;
private subject: Rx.Subject<{}>;

constructor() {
}

public connect(url): Rx.Subject<{}> {
    if (!this.subject) {
        this.subject = this.create(url);
        console.log('Successfully connected: ' + url);
    } else {
        console.log('Already connected: ' + url);
    }
    return this.subject;
}

private create(url): Rx.Subject<MessageEvent> {
    if (this.ws === null) {
        console.log('Connected to WS');
        this.ws = new WebSocket(url);
    } else {
        console.log('Already connected to WS');
    }

    const observable = Rx.Observable.create(
        (obs: Rx.Observer<MessageEvent>) => {
            this.ws.onmessage = obs.next.bind(obs);
            this.ws.onerror = obs.error.bind(obs);
            this.ws.onclose = obs.complete.bind(obs);
            return this.ws.close.bind(this.ws);
        });

    return Rx.Subject.create({}, observable);
}
}

和两个以相同方式订阅int的组件:

// ...
constructor(private stationService: StationService, private websocketService: WebsocketService) {

    websocketService.connect('ws://localhost:8080/ws')
        .subscribe(msg => {
            console.log(msg);
            console.log('[Dashboard] Response from websocket: ' + msg.data);
        });
}
// ...

第二个:

// ...
constructor(private http: HttpClient, private websocketService: WebsocketService) {

    websocketService.connect('ws://localhost:8080/ws')
        .subscribe(msg => {
            console.log(msg);
            console.log('[Station] Response from websocket: ' + msg.data);

        });
}
// ...

我们刷新了,这两个组件调用了我的服务:

已连接到WS websocket.service.ts:26:12    成功连接:ws:// localhost:8080 / ws websocket.service.ts:17:12    已连接:ws:// localhost:8080 / ws

但是当我发送一个东西给套接字时,我只有一个响应者:

[Dashboard]来自websocket的回复:qwerty

有人打电话帮助我找到我的错误吗?

谢谢

1 个答案:

答案 0 :(得分:0)

谢谢你。

我只是更改:

    const observable = Rx.Observable.create(
         (obs: Rx.Observer<MessageEvent>) => {
             this.ws.onmessage = obs.next.bind(obs);
             this.ws.onerror = obs.error.bind(obs);
             this.ws.onclose = obs.complete.bind(obs);
             return this.ws.close.bind(this.ws);
    });

    return Rx.Subject.create({}, observable);

收件人:

    const observable = new Subject<MessageEvent>();

    this.ws.onmessage = (msg) => observable.next(msg);
    this.ws.onerror = (err) => observable.error(err);
    this.ws.onclose = () => observable.complete();

    return observable;

成功了!

如果有人对第一个解决方案无效的原因有更详细的了解,请告诉我。