You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Angular RXJS Websocket向Bitvavo服务器请求数据

实现步骤

1. 修正Service逻辑

RxJS的webSocket实例默认会自动将传入的对象序列化为JSON字符串,无需手动转换格式,修正后的Service代码如下:

import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';

// 替换为你的实际变量配置
const BitvavoWssApiUrl = 'wss://ws.bitvavo.com/v2';

// 定义消息格式类型,可选添加提高类型安全性
interface BitvavoSubscribeMsg {
  action: string;
  channels: Array<{
    name: string;
    interval?: string[];
    markets: string[];
  }>
}

@Injectable({ providedIn: 'root' })
export class BitVavoService {
  private subject: WebSocketSubject<unknown> = webSocket(BitvavoWssApiUrl);
  public messages$ = this.subject.asObservable();

  // 参数改为接收对象类型,不要传字符串
  sendMessage(msg: BitvavoSubscribeMsg) {
    this.subject.next(msg);
  }
}

2. Component逻辑实现

订阅消息时做好数据分类存储,同时注意添加取消订阅逻辑避免内存泄漏:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { BitVavoService } from './bitvavo.service';

@Component({
  selector: 'app-bitvavo-data',
  templateUrl: './bitvavo-data.component.html'
})
export class BitvavoDataComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();
  // 分别存储不同类型的返回数据
  public candleData: any[] = [];
  public orderBookData: any = null;

  constructor(private bitVavoService: BitVavoService) {}

  ngOnInit(): void {
    // 订阅WebSocket消息
    this.bitVavoService.messages$
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (msg: any) => {
          // 根据返回的消息类型分类存储数据
          if (msg.event === 'candle') {
            this.candleData = [...this.candleData, msg.data];
          } else if (msg.event === 'book') {
            this.orderBookData = msg.data;
          }
        },
        error: (err) => console.error('WebSocket连接错误:', err),
        complete: () => console.log('WebSocket连接已关闭')
      });

    // 发送订阅请求,直接传对象即可
    this.bitVavoService.sendMessage({
      action: 'subscribe',
      channels: [
        { name: 'candles', interval: ['1h'], markets: ['BTC-EUR'] },
        { name: 'book', markets: ['BTC-EUR', 'XRP-EUR'] }
      ]
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

3. HTML页面渲染

直接绑定组件中存储的变量即可实现实时更新:

<h3>BTC-EUR 1小时蜡烛数据</h3>
<div *ngIf="candleData.length > 0">
  <table border="1">
    <tr>
      <th>时间</th>
      <th>开盘价</th>
      <th>最高价</th>
      <th>最低价</th>
      <th>收盘价</th>
      <th>成交量</th>
    </tr>
    <tr *ngFor="let candle of candleData.slice(-10); let i = index">
      <td>{{ candle[0] | date:'yyyy-MM-dd HH:mm' }}</td>
      <td>{{ candle[1] }}</td>
      <td>{{ candle[2] }}</td>
      <td>{{ candle[3] }}</td>
      <td>{{ candle[4] }}</td>
      <td>{{ candle[5] }}</td>
    </tr>
  </table>
</div>

<h3>BTC-EUR 订单簿数据</h3>
<div *ngIf="orderBookData">
  <p>买一价:{{ orderBookData.bids[0][0] }} 数量:{{ orderBookData.bids[0][1] }}</p>
  <p>卖一价:{{ orderBookData.asks[0][0] }} 数量:{{ orderBookData.asks[0][1] }}</p>
</div>

内容的提问来源于stack exchange,提问作者QuanDar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 05:36:03