如何从 Bitvavo 使用 Angular RXJS Websockets 请求数据

How to request data with Angular RXJS Websockets from Bitvavo

我正在学习 angular,但无法弄清楚如何使用 RXJS websockets 向 Bitvavo 服务器发送数据请求消息。 https://docs.bitvavo.com/#tag/Websocket

连接已建立(见最后一张图),但我不知道如何通过此消息请求数据:

{"action":"subscribe","channels":[{"name":"candles","interval":["1h"],"markets":["BTC-EUR"]},{"name":"book","markets":["BTC-EUR","XRP-EUR"]}]}

如果有人可以提供示例说明如何从 bitVavo/ 或任何其他服务器获取数据,以及如何在 HTML 中使用这些数据,我们将不胜感激。

api url: wss://ws.bitvavo.com/v2

服务:

  public subject  = webSocket(Variables.BitvavoWssApiUrl);
  public messages$ = this.subject.asObservable();

  sendMessage(msg: string) {
    this.subject.next(msg);
  }

组件:

this.BitVavoService.subject.subscribe(
  msg => console.log(msg), // Called whenever there is a message from the server.
  err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
  () => console.log('complete') // Called when connection is closed (for whatever reason).
);

this.BitVavoService.sendMessage('{"action":"subscribe","channels":[{"name":"candles","interval":["1h"],"markets":["BTC-EUR"]},{"name":"book","markets":["BTC-EUR","XRP-EUR"]}]}');


this.BitVavoService.sendMessage({"action":"subscribe","channels":[{"name":"candles","interval":["1h"],"markets":["BTC-EUR"]},{"name":"book","markets":["BTC-EUR","XRP-EUR"]}]});
console.log(liveData$);

我的火狐浏览器:

邮递员:

您发送消息的方式是正确的:socket.next(...),但是您需要确保订阅了您的套接字。来自 rxjs docs:

Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent

看起来您正在重新实现 RxJS WebSocket 已经提供的功能。您不需要 connect() 方法,也不需要 close() 方法。这是因为socket连接在有订阅者时自动建立,没有订阅者时自动关闭。

此外,您不需要单独的 MessagesSubject,只需从 socket$.

中定义 messages$

您的服务可以简化为:

export class BitVavoControllerService {

  private socket$  = new webSocket(Variables.BitvavoWssApiUrl);
  public messages$ = this.socket$.asObservable();

  sendMessage(msg: any) {
    this.socket$.next(msg);
  }
}

现在,在您的组件中,订阅 messages$ 将自动创建套接字连接,当所有订阅都取消订阅时,套接字连接将关闭。

这就是你做组件的方式:

this.BitVavoService.sendMessage({ "action": "subscribe", "channels": [{ "name": "candles", "interval": ["1h"], "markets": ["BTC-EUR"] }, { "name": "book", "markets": ["BTC-EUR", "XRP-EUR"] }] });



this.BitVavoService.subject.subscribe(
      msg => {
        console.log(msg)
        this.bitVavoWssData = msg;
      }
      , // Called whenever there is a message from the server.
      err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
      () => console.log('complete') // Called when connection is closed (for whatever reason).
    );

现在可以使用了。