Home > Back-end >  .NET Angular Shopping cart
.NET Angular Shopping cart

Time:09-14

I'm writing a website (.NET 6, Angular 14) (an online electronics store) that has a shopping cart. I don't know how to properly implement a shopping cart. It is necessary to write a service for adding device, deleting device, emptying the cart, the total price of cart. Each user should have their own shopping cart and now I don't know how to do it. If I write a service in Angular, then when I update the site, all the devices in the cart that I put in the cart disappear, and if I write on the .net, it turns out that each user should have their own table with baskets. I think there is a correct way to implement this, but I can't find a solution. Please help me what should I do.

Service written with Angular:


  public cartItemList : any =[]
  public deviceList = new BehaviorSubject<any>([]);
  public search = new BehaviorSubject<string>("");

  constructor() { }

  getProducts(){
    return this.deviceList.asObservable();
  }

  setDevice(device : any){
    this.cartItemList.push(...device);
    this.deviceList.next(device);
  }
  addtoCart(device : any){
    this.cartItemList.push(device);
    this.deviceList.next(this.cartItemList);
    this.getTotalPrice();
    console.log(this.cartItemList)
  }
  getTotalPrice() : number{
    let grandTotal = 0;
    this.cartItemList.map((a:any)=>{
      grandTotal  = a.total;
    })
    return grandTotal;
  }
  removeCartItem(device: any){
    this.cartItemList.map((a:any, index:any)=>{
      if(device.id=== a.id){
        this.cartItemList.splice(index,1);
      }
    })
    this.deviceList.next(this.cartItemList);
  }
  removeAllCart(){
    this.cartItemList = []
    this.deviceList.next(this.cartItemList);
  }
}

Service with API:


  public cartItemList : any =[]
  public deviceList = new BehaviorSubject<any>([]);
  public search = new BehaviorSubject<string>("");

  readonly deviceAPIUrl = "https://localhost:7163/api";
  constructor(private http: HttpClient) { }

  getProducts(){
    return this.http.get<ICartDevice[]>(this.deviceAPIUrl   '/cart');
  }

  addToCart(data: any){
    return this.http.put(this.deviceAPIUrl   `/cart/addtocart/${data}`, data);
  }

  getTotalPrice(){
    return this.http.get<number>(this.deviceAPIUrl   '/cart/getTotalPrice');
  }
  
  removeCartItem(id: number | string){
    return this.http.delete<IDevice>(this.deviceAPIUrl   `/cart/removeCartItem/${id}`);
  }

  removeAllCart(){
    return this.http.delete<ICartDevice[]>(this.deviceAPIUrl   '/cart/removeAllCart');
  }
}

API for this Service:

        private readonly DataContext _context;

        public CartController( DataContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<CartDevices>>> GetDevices()
        {
            if (_context.CartTable == null)
            {
                return NotFound();
            }
            return await _context.CartTable.ToListAsync();
        }

        [HttpPut("addToCart/{id}")]
        public async Task<IActionResult> PutDeviceInCart(int id)
        {
            var device = _context.Devices.Find(id);

            if (id != device.Id)
            {
                return BadRequest();
            }

            var newCartDevice = new CartDevices
            {
                Name = device.Name,
                Price = device.Price,
                Image = device.Image,
                ShortDescription = device.ShortDescription,
                FullDescription = device.FullDescription,
                CategoryId = device.CategoryId,
                RAM_ID = device.RAM_ID,
                MemoryId = device.MemoryId,
                Amount = device.Amount
            };

            _context.CartTable.Add(newCartDevice);
            GetTotalPrice();
            await _context.SaveChangesAsync();

            return Ok(newCartDevice);
        }

        [HttpGet("getTotalPrice")]
        public async Task<IActionResult> GetTotalPrice()
        {
            var totalPrice = _context.CartTable.ToList().Sum(p => p.Price);

            return Ok(totalPrice);
        }

        [HttpDelete("removeCartItem/{id}")]
        public async Task<IActionResult> DeleteDevice(int id)
        {
            if (_context.CartTable == null)
            {
                return NotFound();
            }
            var device = await _context.CartTable.FindAsync(id);
            if (device == null)
            {
                return NotFound();
            }

            _context.CartTable.Remove(device);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        [HttpDelete("removeAllCart")]
        public async Task<IActionResult> DeleteAllCart(int id)
        {
            if (_context.CartTable == null)
            {
                return NotFound();
            }

            var devices = await _context.CartTable.ToListAsync();

            foreach (var device in devices)
            {
                if (device == null)
                {
                    return NotFound();
                }

                _context.CartTable.Remove(device);
            }
            await _context.SaveChangesAsync();

            return NoContent();
        }

CodePudding user response:

In Angular, you can use localStorage to store the data. The issue with this approach would be you will lose the data if you login into some other system.

==================================================================

In .NET, you should use a database and store it as a JSON (this way you can avoid multiple rows for each item) and keep track of the status of the cart.

  • Related