首页 > 解决方案 > 将数据从 websocket 分配给变量

问题描述

我正在通过 websocket 流从网站获取数据,我可以在控制台中清楚地看到它作为 Json 对象,现在我想在我的前端显示它,但我不知道该怎么做。我尝试将数据分配给一个变量,但我有点挣扎。这甚至是解决方案吗?

我获取数据的代码如下:

const ws = new WebSocket('wss://ws-feed.pro.coinbase.com');

ws.onopen = function () {
  ws.send(JSON.stringify({
    "type": "subscribe",
    "product_ids": [
      "BTC-USD",
    ],
    "channels": [
      "level2"
    ]
  }));
};

ws.onmessage = function (message) {
 const msg = JSON.parse(message.data);
  console.log(msg)
}

即使我设法在我的应用程序中显示它,它也会作为一个整体出现,我想将对象的每个键/值对拆分为不同的变量以正确设置它的样式,我该怎么做?

非常感谢

标签: javascriptwebsocketsvelte

解决方案


您需要将数据存储在变量中并
通过更改 html 元素的 innerText 字段来更新 ui <div id="app"></div>

const ws = new WebSocket("wss://ws-feed.pro.coinbase.com");

ws.onopen = function () {
  ws.send(
    // changed the request a bit because my pc could not handle
    // the amount of the messages (1 per 0.1ms)
    JSON.stringify({
      type: "subscribe",
      channels: [{ name: "status" }]
    })
  );
};

// used for a conditional rendering.
let isFirst = false;

ws.onmessage = function (message) {
  /**
   * destruct currencies value from the data.
   * same as:
   * const currencies = message.data.currencies
   */
  const { currencies } = JSON.parse(message.data);

  /**
   * get the name of the first or second object in the currencies array.
   */
  if (currencies && currencies.length > 0) {
    const index = isFirst ? 0 : 1;

    const name = currencies[index].name;

    // update is first
    isFirst = !isFirst;

    /**
     * find the html element you want to update.
     * update the UI.
     */
    document.getElementById("app").innerHTML = `
        <h1>First coin on the list is <span>${name}</span></h1>
      `;
  }
};


推荐阅读