I want to display the data from my backend to the front end. It's working but I am making a shopping cart system in Angular using help from a youtube video. I have poor knowledge of Observables and stuff related to it. For the Youtuber, the data is displayed. The only difference between the youtube project and mine is that he is using a fake store API and I am using a database and getting products from the backend.
My cart.component.ts file
import { Component, OnInit } from '@angular/core';
import { CartService } from 'src/services/cart.service';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
products: any = [];
allProducts: any = 0;
constructor(private cartService: CartService) { }
ngOnInit(): void {
this.cartService.getProductData().subscribe(res => {
this.products = res;
this.allProducts = this.cartService.getTotalAmount();
})
}
removeProduct(item: any) {
this.cartService.removeCartData(item);
}
removeAllProducts() {
this.cartService.removeAllCart();
}
}
My cart.service.ts file
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
cartDataList: any = [];
productList = new BehaviorSubject<any>([]);
constructor() { }
// Get cart data
getProductData() {
return this.productList.asObservable();
}
// Set cart data
setProduct(product: any) {
this.cartDataList.push(...product);
this.productList.next(product);
}
// Add products to cart
addToCart(product: any) {
this.cartDataList.push(product);
this.productList.next(this.cartDataList);
this.getTotalAmount();
console.log(this.cartDataList);
}
// Calculate total amount
getTotalAmount() {
let grandTotal = 0;
this.cartDataList.map((a: any) => {
grandTotal += a.total;
});
}
// Remove product one by one
removeCartData(product: any) {
this.cartDataList.map((a: any, index: any) => {
if (product.id === a.id) {
this.cartDataList.splice(index, 1);
}
})
}
// Empties the whole cart
removeAllCart() {
this.cartDataList = [];
this.productList.next(this.cartDataList);
}
}
I know the problem is in getProductData() function but I don't know how to fix it. Also if you need any other file that may help feel free to ask and yes this is my very first post asking a question.
productList = new BehaviorSubject([]); getProductData$ = this.productList.asObservable();
do not use this.productList.asObservable() in a function declare it as a variable.