Angular 2 share websocket service across components

社会主义新天地 提交于 2019-12-04 07:21:12

It seems that your observable create function is called multiple times, most probably two components => two subscriptions => two observable create function invocations. So the latest observable create fn overrides previous observable callbacks to websocket onmessage, onerror and onclose. You should multicast the underlying observable to prevent that (share operator should do the trick).

        // bind ws events to observable (streams)
        let observable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
            ws.onmessage = obs.next.bind(obs);
            ws.onerror = obs.error.bind(obs);
            ws.onclose = obs.complete.bind(obs);

            return ws.close.bind(ws);
        }).share();

More useful resources of how to do this properly https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts https://github.com/blesh/RxSocketSubject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!