溫馨提示×

SignalR怎么實現庫存更新與購物車同步

小億
93
2024-05-09 16:11:01
欄目: 編程語言

要實現庫存更新與購物車同步,可以使用SignalR來實現實時通信。以下是一個簡單的示例:

  1. 首先,在后端代碼中創建一個SignalR Hub,用于處理客戶端發送的請求和更新庫存信息。
public class InventoryHub : Hub
{
    // 更新庫存信息
    public void UpdateInventory(int productId, int quantity)
    {
        // 更新數據庫中的庫存信息

        // 向所有客戶端發送更新的庫存信息
        Clients.All.SendAsync("UpdateInventory", productId, quantity);
    }
}
  1. 在前端代碼中,連接到SignalR Hub,并監聽來自Hub的更新消息,然后更新購物車信息。
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/inventoryHub")
    .build();

connection.start().then(() => {
    console.log("Connected to InventoryHub");

    connection.on("UpdateInventory", (productId, quantity) => {
        // 更新購物車信息
        console.log(`Product ${productId} inventory updated to ${quantity}`);
    });
}).catch(err => console.error(err));
  1. 當用戶在購物車中增加或減少商品數量時,調用后端Hub的UpdateInventory方法更新庫存信息。
// 增加商品數量
function addToCart(productId) {
    // 更新庫存數量
    connection.invoke("UpdateInventory", productId, -1)
        .catch(err => console.error(err));
}

// 減少商品數量
function removeFromCart(productId) {
    // 更新庫存數量
    connection.invoke("UpdateInventory", productId, 1)
        .catch(err => console.error(err));
}

通過以上步驟,就可以實現庫存更新與購物車同步的功能。當用戶修改購物車中商品數量時,庫存信息會實時更新,確保購物車中的商品數量與庫存信息保持同步。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女