Angular2/Websocket: how to return an observable for incoming websocket messages

前端 未结 2 1470
忘了有多久
忘了有多久 2021-02-02 02:20

I\'m going to use Angular2 to receive websocket incoming messages and update a webpage based on those received messages. Right now, I\'m using a dummy echo websocket service and

2条回答
  •  难免孤独
    2021-02-02 02:33

    I put it on a plunker and I added a function for sending message to the Websocket endpoint. Here is the important edit:

    public GetInstanceStatus(): Observable{
        this.websocket = new WebSocket("ws://echo.websocket.org/"); //dummy echo websocket service
        this.websocket.onopen =  (evt) => {
            this.websocket.send("Hello World");
        };
        return Observable.create(observer=>{
            this.websocket.onmessage = (evt) => { 
                observer.next(evt);
            };
        })
        .share();
    }
    

    Update
    As you mentioned in your comment, a better alternative way is to use Observable.fromEvent()

    websocket = new WebSocket("ws://echo.websocket.org/");
    public GetInstanceStatus(): Observable{
        return Observable.fromEvent(this.websocket,'message');
    }
    

    plunker example for Observable.fromEvent();

    Also, you can do it using WebSocketSubject, although, it doesn't look like it's ready yet (as of rc.4):

    constructor(){
      this.websocket = WebSocketSubject.create("ws://echo.websocket.org/");
    }
    
    public sendMessage(text:string){
      let msg = {msg:text};
      this.websocket.next(JSON.stringify(msg));
    } 
    

    plunker example

提交回复
热议问题