猿问

有没有一种方法可以合并单据值(购物车的总价格和数量)

如标题所述,在显示价格和数量方面存在问题。这是我到目前为止所做的:


购物车项目


 export class ShoppingCartItem {

  id?: string;

  name: string;

  imgCover: string;

  price: number;

  quantity: number;

}

购物车服务


async getCart(): Promise<Observable<ShoppingCartItem[]>> {

  let cartId =  await this.getOrCreateCartId();

  let cartCollection = this.afs.collection(`shopping-carts/${cartId}/items`, ref => ref.where('id','==', cartId));

  return cartCollection.snapshotChanges().pipe(map( actions => {

    return actions.map(a => {

      const data = a.payload.doc.data() as ShoppingCartItem;

      const id = a.payload.doc.id;


      return { id, ...data };

    });

  })

);

}

navbar.component


  totalCart$: Observable<ShoppingCartItem[]>;

  items: ShoppingCartItem[]

  total: number = 0;


  constructor(

   public dialog: MatDialog,

   private shoppingCartService: ShoppingCartService,

  ) {}


  ngOnInit() {

    this.getCart();

  }


  async getCart() {

    this.totalCart$ = await this.shoppingCartService.getCart();


    this.totalCart$.subscribe(data => {

      data.forEach(element => {

       this.total += element.quantity


       console.log(this.total);

   })

  })

 }

使用这种方法,我可以在第一次加载时显示正确的数据,然后将该数量乘以相同数量+ 1(因为再次调用现有数据)就可以显示正确的数据。如何合并数量和价格字段?


胡子哥哥
浏览 130回答 1
1回答

智慧大石

为了防止总数在以后的通话中增加一倍,只需添加一个局部变量即可将您的数量和价格相加。完成价格和数量的累加后,您可以为它们分配实际的类别字段,请参见下面的示例:totalCart$: Observable<ShoppingCartItem[]>;items: ShoppingCartItem[]totalQuantity: number = 0;totalPrice: number = 0;constructor(&nbsp; public dialog: MatDialog,&nbsp; private shoppingCartService: ShoppingCartService,) { }ngOnInit() {&nbsp; this.getCart();}async getCart() {&nbsp; this.totalCart$ = await this.shoppingCartService.getCart();&nbsp; this.totalCart$.subscribe(data => {&nbsp; &nbsp; let totalQuantity = 0;&nbsp; &nbsp; let totalPrice = 0;&nbsp; &nbsp; data.forEach(element => {&nbsp; &nbsp; &nbsp; totalQuantity += element.quantity&nbsp; &nbsp; &nbsp; totalPrice += element.quantity * element.price&nbsp; &nbsp; &nbsp; console.log(totalQuantity, totalPrice);&nbsp; &nbsp; })&nbsp; &nbsp; this.totalQuantity = totalQuantity;&nbsp; &nbsp; this.totalPrice = totalPrice;&nbsp; })}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答