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

前端 未结 2 1467
忘了有多久
忘了有多久 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<any>{
        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<Event>{
        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

    0 讨论(0)
  • 2021-02-02 02:37

    Get onMessage data from socket.

    import { Injectable } from '@angular/core';
    import {Observable} from 'rxjs/Rx';
    
    
    @Injectable()
    
    export class HpmaDashboardService {
    private socketUrl: any = 'ws://127.0.0.0/util/test/dataserver/ws';
    private websocket: any;      
    
    public GetAllInstanceStatus(objStr): Observable<any> {
          this.websocket = new WebSocket(this.socketUrl);
          this.websocket.onopen =  (evt) => {
            this.websocket.send(JSON.stringify(objStr));
          };
          return Observable.create(observer => {
            this.websocket.onmessage = (evt) => {
              observer.next(evt);
            };
          }).map(res => res.data).share();
     }
    
    **Get only single mesage from socket.**
    
        public GetSingleInstanceStatus(objStr): Observable<any> {
          this.websocket = new WebSocket(this.socketUrl);
          this.websocket.onopen =  (evt) => {
            this.websocket.send(JSON.stringify(objStr));
          };
          return Observable.create(observer => {
            this.websocket.onmessage = (evt) => {
              observer.next(evt);
              this.websocket.close();
            };
          }).map(res => res.data).share();
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题