AllAngular

Angular Part 5: Create Product Cart Page in Angular & API URL | Create EAccessoriesShop Angular

Angular Part 5: Create Product Cart Page in Angular & API URL | Create EAccessoriesShop Angular

Here’s an example of how you can create a product cart page in an Angular app and use an API endpoint to store and retrieve the cart data:

  1. Create a new component for the cart page, let’s call it cart-page. You can do this by running the following command:
ng generate component cart-page

In the cart-page component’s class (cart-page.component.ts), you can create an array to store the products in the cart, and a function to add products to the cart.

In your cart-page.component.ts file, you can create the function getCartFromApi() and saveCartToApi() to handle the API calls. To make the API calls, you can use HttpClient module from @angular/common/http

cart.component.ts

import { Component, OnInit } from '@angular/core';
import { CartModel } from '../models/cart.model';
import { CartService } from '../services/cart.service';
import { Route, Router, RouterLink } from '@angular/router';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css'],
  providers:[CartService]
})
export class CartComponent implements OnInit {

  cartProduct_list:CartModel[]=[]
  constructor(private http_service:CartService,private router : Router) {
  }

  ngOnInit(): void {
  this.http_service.getCartProducts().subscribe((data)=>this.cartProduct_list=data['result'])
  }

 checkOutItem(cid:number){
  this.router.navigate(["/checkout"]);
  }
  
removeItem(cid:number){
  this.http_service.removeCartItem(cid);
}

}

In the cart-page component’s template (cart-page.component.html), you can display the products in the cart using the *ngFor directive.

cart.component.html

<div class="container">
    <table class="m-2 table table-striped ">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Pid</th>
                <th>Title</th>
                <th>Price</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <ng-container *ngFor="let cart of cartProduct_list">
                <tr>
                <td>{{cart.id}}</td>
                <td>{{cart.pid}}</td>
                <th>{{cart.title | slice:0:100}}</th>
                <th>{{cart.price}}</th>
                <td><button class="btn btn-warning" type="submit" (click)="checkOutItem(cart.id)">Check Out</button></td>
            </tr>
            </ng-container>
        </tbody>
    </table>
</div>

Finally, in your app-routing.module.ts file, add a new route for the cart-page component.

import { CartPageComponent } from './cart-page/cart-page.component';

Leave a ReplyCancel reply

Exit mobile version