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

前端 未结 2 1506
忘了有多久
忘了有多久 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: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 {
          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 {
          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();
      }
    
    }
    

提交回复
热议问题