Websocket事件仅由一个组件捕获
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Websocket事件仅由一个组件捕获相关的知识,希望对你有一定的参考价值。
我在Angular7中有一个websocket服务
import { environment } from './../../../environments/environment.prod';
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs';
import {map} from 'rxjs/operators';
@Injectable()
export class WsService{
public wsMessages: Rx.Subject<any>;
public connect(url): Rx.Subject<MessageEvent> {
if(!this.subject){
this.subject = this.create(url);
console.log("Websocket (Dashboard) successfully connected to : ", url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(
url,
[`Bearer`, `${this.token.substring(7)}`]
);
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);
}
)
let observer = {
next: (data: Object) => {
if(ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
private token: string;
constructor(){
this.token = JSON.parse(localStorage.getItem('user')).token
this.wsMessages = <Rx.Subject<any>>
this.connect(`${environment.websocketUrl}/dashboard/ws`)
.pipe(
map((response: MessageEvent): any =>{
let data = JSON.parse(response.data);
return data;
})
)
}
private subject: Rx.Subject<MessageEvent>;
}
我有多个订阅qazxsw poi的组件
wsMessages
事件只打印在一个组件上,我需要很多组件来监听那些ws事件。
好了,在对这个主题做了一些阅读之后,我发现有一个 this.ws.wsMessages.subscribe(msg => {
this.catchWebSocketEvents(msg)
console.log("LeftBarSocket : ", msg);
})
函数允许多个订阅者共享一个源。
解决方案在这里:
share()
只需要将 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);
}
).pipe(
share()
)
添加到observable中,即可创建。
以上是关于Websocket事件仅由一个组件捕获的主要内容,如果未能解决你的问题,请参考以下文章
Vue.js 在 websocket onmessage 事件中更新 html
“未捕获的类型错误:无法在 Websocket Angular JS 上读取未定义的属性‘延迟’”