Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
How can I display data in the shopping cart in Angular?

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

do not use this.productList.asObservable() in a function declare it as a variable.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda