【问题标题】:adding product to shopping cart in angular 6以角度 6 将产品添加到购物车
【发布时间】:2018-12-19 22:47:49
【问题描述】:

我正在尝试将产品添加到购物车,但我得到:'$exists 属性在 AngularFireObject 类型上不存在'。产品已添加到购物车,但如果它存在于购物车中,则仅更新数量。我正在使用 Angular 6 和 Firebase,但我使用的教程是 Angular 4。

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Product } from '../models/product';
import { take } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {
  constructor(private db: AngularFireDatabase) { }

  private create() {
   return  this.db.list('/shopping-carts').push({
      dateCreated: new Date().getTime()
    });
  }

 async getCart() {
   const cartId = await this.getOrCreateCartId();
  return this.db.object('/shopping-carts/' + cartId).valueChanges();
}

private getItem(cartId, productId: string) {
  return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}

  private async getOrCreateCartId(): Promise<string> {
    const cartId = localStorage.getItem('cartId');
    if (cartId) { return cartId; }
    const result = await this.create();
    localStorage.setItem('cartId', result.key);
    return result.key;

  }

 async addToCart(product: Product) {
     const cartId =  await this.getOrCreateCartId();
     const item$ = this.getItem(cartId, product.key);
     item$.pipe(take(1)).subscribe(
       item => {
         if(item$.$exists) {
           item$.update({ quantity: quantity + 1 });
         } else {
           item$.set({ product: product, quantity: 1});
         }
       }
     );
  }
}

shopping-cart.service.ts =>

import { Component, Input } from '@angular/core';
import { Product } from '../models/product';
import { ShoppingCartService } from '../services/shopping-cart.service';

@Component({
  selector: 'app-product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.css']
})

    export class ProductCardComponent {
      @Input('product') product: Product;
      @Input() showActions = true;
      @ Input() shoppingCart;

      constructor(private cartService: ShoppingCartService) { }

      addToCart() {
        this.cartService.addToCart(this.product);
      }

      getQuantity() {
        if (!this.shoppingCart) { return 0; }
        const item = this.shoppingCart.items[this.product.key];

        return item ? item.quantity : 0;
      }

}

product-card.components.ts =>

【问题讨论】:

  • 尝试return this.db.object('/shopping-carts/' + cartId + '/items/' + productId); 您不必获取返回数据,您知道这是要更新或设置的正确对象。 Snapshotchanges 和 valuechanges 仅用于获取数据而不更新或设置它。
  • 有没有办法检查firebase中是否存在对象?
  • 嗯,你可以先用 snapshotchanges 获取对象,然后不用

标签: angular firebase-realtime-database


【解决方案1】:

你需要使用item$.exists()而不是item$.$exists

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 2012-06-09
    • 1970-01-01
    • 2011-12-19
    • 2014-11-21
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多