Angular2/Websocket:如何为传入的websocket消息返回一个observable

Bin*_* Lu 9 websocket observable angular

我将使用Angular2接收websocket传入消息并根据收到的消息更新网页.现在,我正在使用虚拟回声websocket服务并将替换它.

根据我的理解,接收websocket消息的函数必须返回由将更新网页的处理程序订阅的observable.但我无法弄清楚如何返回一个可观察的.

代码段附于下方.在MonitorService创建一个WebSocket连接,并返回可观察到包含接收到的消息.

@Injectable()
export class MonitorService {

    private actionUrl: string;
    private headers: Headers;
    private websocket: any;
    private receivedMsg: any;
    constructor(private http: Http, private configuration: AppConfiguration) {

        this.actionUrl = configuration.BaseUrl + 'monitor/';
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

    public GetInstanceStatus = (): Observable<Response> => {
        this.websocket = new WebSocket("ws://echo.websocket.org/"); //dummy echo websocket service
        this.websocket.onopen =  (evt) => {
            this.websocket.send("Hello World");
        };

        this.websocket.onmessage = (evt) => { 
            this.receivedMsg = evt;
        };

        return new Observable(this.receivedMsg).share();
    }

}
Run Code Online (Sandbox Code Playgroud)

下面是另一个订阅从上面返回的observable并相应更新网页的组件.

export class InstanceListComponent {
  private instanceStatus: boolean
  private instanceName: string
  private instanceIcon: string
  constructor(private monitor: MonitorService) { 
    this.monitor.GetInstanceStatus().subscribe((result) => {
        this.setInstanceProperties(result);
    });
  }

  setInstanceProperties(res:any) {
    this.instanceName = res.Instance.toUpperCase();
    this.instanceStatus = res.Status;
    if (res.Status == true)
    {
      this.instanceIcon = "images/icon/healthy.svg#Layer_1";
    } else {
      this.instanceIcon = "images/icon/cancel.svg#cancel";
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我在浏览器控制台中遇到了这个错误 TypeError: this._subscribe is not a function

Abd*_*yer 10

我把它放在一个plunker上,我添加了一个向Websocket端点发送消息的功能.这是重要的编辑:

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();
}
Run Code Online (Sandbox Code Playgroud)

更新
正如您在评论中提到的,更好的替代方法是使用Observable.fromEvent()

websocket = new WebSocket("ws://echo.websocket.org/");
public GetInstanceStatus(): Observable<Event>{
    return Observable.fromEvent(this.websocket,'message');
}
Run Code Online (Sandbox Code Playgroud)

plunker示例Observable.fromEvent();

此外,您可以使用它WebSocketSubject,但它看起来还没有准备好(从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));
} 
Run Code Online (Sandbox Code Playgroud)

掠夺者的例子