如何在Angular中显示购物车中的数据?



我想显示从后端到前端的数据。它正在工作,但我正在使用youtube视频的帮助在Angular中制作购物车系统。我对可观察对象和与之相关的东西知之甚少。对于Youtuber,显示数据。youtube项目和我的项目之间唯一的区别是,他使用的是一个假的商店API,而我使用的是一个数据库,并从后端获取产品。

我的cart.component.ts文件

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);
}
}

我知道问题是在getProductData()函数,但我不知道如何修复它。此外,如果你需要任何其他文件可能会有所帮助,请随时询问,是的,这是我第一次问问题。

productList = new BehaviorSubject([]);$ = this.productList.asObservable();

不要在函数中使用this.productList.asObservable(),声明它为一个变量。

最新更新