Angular Part 6-1: Add Product In Cart And Update Table Using Flask API | Create Ecommerce Angular
Table of Contents
Shopping Cart
In a same way we have created PorductList component — we will create now a ShoppingCart component. Just copy the product-list.component.ts and modify it accordingly:
cart.product.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>
cart.comonent.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);
}
}
create a model for cart
cart.model.ts
export interface CartModel{
id?:number,
pid:number,
title?:string,
price?:number,
}
cart.service.ts
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { CartModel } from "../models/cart.model";
@Injectable()
export class CartService{
cart_baseLink="http://localhost:5000/"
cartModel:CartModel;
http_cartservice:HttpClient
constructor(private http_client:HttpClient){
this.http_cartservice=http_client;
}
getCartProducts()
{
let httpOptions={
headers:new HttpHeaders({
'Content-Type':"application/json"
})
}
return this.http_cartservice.get(this.cart_baseLink+'cart',httpOptions)
}
addToCartProduct(pid:any){
let httpOptions={
data:{'pid':pid},
// headers:new HttpHeaders({
// 'Content-Type':"application/json"
// })
}
return this.http_cartservice.post(this.cart_baseLink+'cart',httpOptions).subscribe();
}
removeCartItem(cid:number){
return this.http_cartservice.delete(this.cart_baseLink+'cart/'+cid).subscribe();
}
}
Pingback: Angular 16 Is Launch: Discover the Top 7 Features | Angular Developer - SoftwareTechIT
Pingback: Create A Angular Reactive Form Login | Login Form Using Bootstrap And Angular - SoftwareTechIT