RxJs Observable with WebSocket

前端 未结 4 955
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 14:01

My angular application uses a websocket to communicate with the backend.

In my test case I have 2 client components. The Observable timer prints two different clie

4条回答
  •  难免孤独
    2020-12-16 14:41

    As of rxjs 5 you can use the built-in websocket feature which creates the subject for you. It also reconnects when you resubscribe to the stream after an error. Please refer to this answer:

    https://stackoverflow.com/a/44067972/552203

    TLDR:

     let subject = Observable.webSocket('ws://localhost:8081');
     subject
       .retry()
       .subscribe(
          (msg) => console.log('message received: ' + msg),
          (err) => console.log(err),
          () => console.log('complete')
        );
     subject.next(JSON.stringify({ op: 'hello' }));
    

提交回复
热议问题