Websocket事件仅由一个组件捕获

时间:2019-01-15 13:47:25

标签: javascript angular websocket rxjs observable

我在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>;

}

而且我有多个订阅wsMessages

的组件
 this.ws.wsMessages.subscribe(msg => {
    this.catchWebSocketEvents(msg)
    console.log("LeftBarSocket : ", msg);
  })

事件仅打印在一个组件上,我需要许多组件来监听那些ws事件。

1 个答案:

答案 0 :(得分:0)

好了,在对主题进行了一些阅读之后,我发现有一个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()
    )

只需将.pipe(share())添加到正在创建的观察对象中即可。