src/app/cart/cart.component.ts
OnInit
selector | app-cart |
styleUrls | ./cart.component.css |
templateUrl | ./cart.component.html |
Properties |
Methods |
Accessors |
constructor(http: HttpClient, route: ActivatedRoute, router: Router, cartService: CartService, authService: AuthService)
|
||||||||||||||||||
Defined in src/app/cart/cart.component.ts:39
|
||||||||||||||||||
Parameters :
|
calculateTotalPrice |
calculateTotalPrice()
|
Defined in src/app/cart/cart.component.ts:61
|
Returns :
number
|
clearCart |
clearCart()
|
Defined in src/app/cart/cart.component.ts:187
|
Returns :
void
|
completeOrder |
completeOrder()
|
Defined in src/app/cart/cart.component.ts:159
|
Returns :
void
|
decreaseQuantity | ||||||
decreaseQuantity(item: CartItem)
|
||||||
Defined in src/app/cart/cart.component.ts:85
|
||||||
Parameters :
Returns :
void
|
getCartItems |
getCartItems()
|
Defined in src/app/cart/cart.component.ts:122
|
Returns :
void
|
getOrderData |
getOrderData()
|
Defined in src/app/cart/cart.component.ts:221
|
Returns :
Order
|
getTotalItems |
getTotalItems()
|
Defined in src/app/cart/cart.component.ts:73
|
Returns :
number
|
increaseQuantity | ||||||
increaseQuantity(item: CartItem)
|
||||||
Defined in src/app/cart/cart.component.ts:96
|
||||||
Parameters :
Returns :
void
|
ngOnInit |
ngOnInit()
|
Defined in src/app/cart/cart.component.ts:54
|
Returns :
void
|
placeOrder |
placeOrder()
|
Defined in src/app/cart/cart.component.ts:149
|
Returns :
void
|
removeFromCart | ||||||
removeFromCart(item: CartItem)
|
||||||
Defined in src/app/cart/cart.component.ts:99
|
||||||
Parameters :
Returns :
void
|
updateCartData |
updateCartData()
|
Defined in src/app/cart/cart.component.ts:137
|
Returns :
void
|
viewAllOrders |
viewAllOrders()
|
Defined in src/app/cart/cart.component.ts:202
|
Returns :
void
|
viewOrders |
viewOrders()
|
Defined in src/app/cart/cart.component.ts:193
|
Returns :
void
|
Private _isLoggedIn |
Type : boolean
|
Default value : false
|
Defined in src/app/cart/cart.component.ts:39
|
address |
Type : string
|
Defined in src/app/cart/cart.component.ts:34
|
areCartItemsAvailable |
Type : boolean
|
Defined in src/app/cart/cart.component.ts:29
|
cart |
Type : Cart | any
|
Defined in src/app/cart/cart.component.ts:26
|
cartItems |
Type : CartItem[]
|
Defined in src/app/cart/cart.component.ts:28
|
item |
Type : MenuItem | any
|
Defined in src/app/cart/cart.component.ts:27
|
order |
Type : Order[]
|
Default value : []
|
Defined in src/app/cart/cart.component.ts:33
|
orderId |
Type : string
|
Defined in src/app/cart/cart.component.ts:32
|
phone |
Type : string
|
Defined in src/app/cart/cart.component.ts:35
|
selectedPaymentMethod |
Type : "online" | "cash-on-delivery"
|
Default value : 'online'
|
Defined in src/app/cart/cart.component.ts:37
|
userId |
Type : string
|
Defined in src/app/cart/cart.component.ts:31
|
isLoggedIn |
getisLoggedIn()
|
Defined in src/app/cart/cart.component.ts:217
|
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { Cart, CartItem } from '../Cart';
import { CartService } from '../cart.service';
import { AuthService } from '../auth.service';
import { MenuItem } from '../MenuItem';
export interface Order {
_id: string;
user: string;
cart: string;
status: 'Pending' | 'Processing' | 'Shipped' | 'Delivered';
createdAt: Date;
paymentMethod: 'online' | 'cash-on-delivery';
address: string;
phone: string;
}
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css'],
})
export class CartComponent implements OnInit {
cart: Cart | any;
item:MenuItem|any;
cartItems: CartItem[];
areCartItemsAvailable: boolean;
userId!: string;
orderId!: string;
order: Order[] = [];
address: string;
phone: string;
selectedPaymentMethod: 'online' | 'cash-on-delivery' = 'online';
private _isLoggedIn: boolean = false;
constructor(
private http: HttpClient,
private route: ActivatedRoute,
private router: Router,
private cartService: CartService, // Inject the CartService
private authService: AuthService // Inject the CartService
) {
const token = localStorage.getItem('token');
if (token) {
this._isLoggedIn = true;
}
}
ngOnInit(): void {
this.route.params.subscribe((params) => {
this.userId = params['userId'];
this.getCartItems(); // Move the call to getCartItems() here
});
}
calculateTotalPrice(): number {
let totalPrice = 0;
if (this.cart) {
for (let item of this.cart.items) {
totalPrice += item.menuItem.price * item.quantity;
}
}
return totalPrice;
}
getTotalItems(): number {
let totalItems = 0;
if (this.cart) {
for (let item of this.cart.items) {
totalItems += item.quantity;
}
}
return totalItems;
}
decreaseQuantity(item: CartItem): void {
if (item.quantity > 0) {
item.quantity--;
}
}
increaseQuantity(item: CartItem): void {
item.quantity++;
}
removeFromCart(item: CartItem): void {
if (this.cart) {
const index = this.cart.items.indexOf(item);
if (index !== -1) {
this.cart.items.splice(index, 1);
// Update the cart data in the backend
this.authService.updateCart(this.cart).subscribe(
() => {
console.log('Cart updated successfully');
},
(error) => {
console.error('Error updating cart:', error);
}
);
this.updateCartData(); // Update cart data in the component
}
}
}
getCartItems() {
this.authService.getCartItems().subscribe(
(response: any) => {
this.cart = response.cart; // Assign the response directly to the cart property
this.cartItems = this.cart.items; // Access the items property of the cart object
console.log(this.cartItems);
this.areCartItemsAvailable = this.cartItems.length > 0;
console.log('Are cart items available?', this.areCartItemsAvailable);
},
(error) => {
console.error('An error occurred:', error);
}
);
}
updateCartData(): void {
if (this.cart && Array.isArray(this.cart.items)) {
this.cartItems = [...this.cart.items];
this.areCartItemsAvailable = true;
} else {
this.cartItems = [];
this.areCartItemsAvailable = false;
}
console.log(this.cartItems); // Update the console.log statement to check the cartItems
}
placeOrder() {
if (this.selectedPaymentMethod === 'online') {
this.router.navigate(['/payment'], {
state: { orderData: this.getOrderData() },
});
} else {
this.completeOrder();
}
}
completeOrder(): void {
const orderData = this.getOrderData();
this.http.post<Order>('http://localhost:3000/orders', orderData).subscribe(
(response) => {
console.log('Order placed successfully');
alert('Order placed successfully');
console.log(response)
// Update the cart data in the backend
this.authService.updateCart(this.cart).subscribe(
() => {
console.log('Cart updated successfully');
},
(error) => {
console.error('Error updating cart:', error);
}
);
this.clearCart();
localStorage.setItem('orderId', response._id);
this.orderId = response._id;
this.router.navigate(['/orders', this.userId, this.orderId]);
},
(error) => {
console.error('Error placing order:', error);
}
);
}
clearCart(): void {
if (this.cart) {
this.cart.items = [];
}
}
viewOrders() {
const orderId = localStorage.getItem('orderId');
if (orderId) {
this.router.navigate(['/orders', this.userId, orderId]);
} else {
console.error('Order ID is undefined');
}
}
viewAllOrders() {
this.http
.get<Order[]>(`http://localhost:3000/orders/user/${this.userId}`)
.subscribe(
(orders) => {
this.order = orders;
this.router.navigate(['/orders', this.userId]);
console.log('Retrieved orders:', orders);
},
(error) => {
console.error('Error retrieving orders:', error);
}
);
}
get isLoggedIn() {
return this._isLoggedIn;
}
getOrderData(): Order {
return {
_id: '',
user: this.userId,
cart: '',
status: 'Pending',
createdAt: new Date(),
paymentMethod: this.selectedPaymentMethod,
address: this.address,
phone: this.phone,
};
}
}
<div class="container" *ngIf="isLoggedIn">
<h1 class="mb-4">Your Cart Items</h1>
<ng-container *ngIf="areCartItemsAvailable; else emptyCart">
<div class="row">
<div class="col-lg-4 mb-3" *ngFor="let item of cartItems">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ item.menuItem.name }}</h5>
<hr>
<p class="card-text">Price: {{ item.menuItem.price | currency:'INR':'symbol' }}</p>
<div class="quantity-control">
<button class="btn btn-sm btn-danger" (click)="decreaseQuantity(item)"><i class="bi bi-dash"></i></button>
<p class="card-text">Quantity: {{ item.quantity }}</p>
<button class="btn btn-sm btn-success" (click)="increaseQuantity(item)"><i class="bi bi-plus"></i></button>
</div>
</div>
<hr>
<button class="btn btn-danger" (click)="removeFromCart(item)"><i class="bi bi-trash"></i> Remove</button>
</div>
</div>
</div>
</ng-container>
<ng-template #emptyCart>
<div class="col-lg-12">
<p>Your cart is empty.</p>
</div>
</ng-template>
<div class="mt-4">
<p>Total Items: {{ getTotalItems() }}</p>
<p>Total Price: {{ calculateTotalPrice() | currency:'INR':'symbol' }}</p>
</div>
<label for="address">Enter Delivery Address:</label>
<input type="text" id="address" [(ngModel)]="address" name="address" class="form-control">
<label for="phoneNumber">Phone Number:</label>
<input type="text" id="phone" [(ngModel)]="phone" name="phone" class="form-control">
<label for="paymentMethod">Payment Method:</label>
<select id="paymentMethod" [(ngModel)]="selectedPaymentMethod" name="paymentMethod" class="form-control">
<option value="online">Online Payment</option>
<option value="cash-on-delivery">Cash on Delivery</option>
</select>
<div class="mt-3">
<button class="btn btn-primary" (click)="placeOrder()"><i class="bi bi-check2"></i> Place Order</button>
<button class="btn btn-secondary" (click)="viewAllOrders()"><i class="bi bi-list"></i> View All Orders</button>
</div>
</div>
./cart.component.css
/* Custom styles for the menu items */
.container {
padding: 20px;
}
.card {
margin-bottom: 10px;
}
.card-title {
font-size: 1.2rem;
font-weight: bold;
}
.card-text {
margin-bottom: 5px;
}
/* Custom styles for the buttons */
.btn-primary {
margin-right: 10px;
}
.btn-secondary {
margin-right: 10px;
}
/* Custom styles for the cart items */
.cart-item {
margin-bottom: 10px;
}
.cart-item p {
margin-bottom: 5px;
}
/* Additional custom styles */
/* Add your own custom styles here */
/* style.css */
/* Margin and padding for the alert */
.alert {
margin-bottom: 20px;
padding: 10px;
}
/* Margin and padding for the container */
.container {
margin-top: 20px;
padding: 20px;
}
/* Margin and padding for the cart item card */
.card {
margin-bottom: 20px;
padding: 10px;
}
/* Margin and padding for the input fields */
input {
margin-bottom: 10px;
padding: 5px;
}
/* Margin and padding for the buttons */
.btn {
margin-right: 10px;
padding: 8px 16px;
}