gpt4 book ai didi

javascript - 错误类型错误 : Cannot read property '-LlWio7vFBuxfeviKdWa' of undefined

转载 作者:行者123 更新时间:2023-12-02 23:11:03 24 4
gpt4 key购买 nike

将产品添加到购物车(最终托管在 Firebase 中)时,我收到此错误。我正在遵循本教程,但我似乎无法理解我错过了什么;该对象是在 firebase 中创建的,但错误仍然存​​在,并且我无法显示购物车中的产品数量...

enter image description here

产品组件的 TS:´

    constructor(
private productService: ProductService,
private route: ActivatedRoute,
private shoppingCartService: ShoppingCartService) {



this.productService.getAll().subscribe(products => {
this.products = products;
route.queryParamMap.subscribe(params => {
this.category = params.get('category');

});
})
}

async ngOnInit() {
this.subscription = (await this.shoppingCartService.getCart())
.subscribe(cart =>{
this.cart = cart;
console.log(cart)
})

}



addToCart(product: Product){
this.cartService.addToCart(product);
console.log(this.shoppingCart)
let item = this.shoppingCart.item[this.product.$key];
console.log(item)
}

HTML:

<button 
(click)="addToCart(product)"

class="btn btn-primary btn-block">
Add to cart
</button>
<div>{{getQuantity()}}</div>

服务:

constructor(private db: AngularFireDatabase) { }

private create() {
return this.db.list('/shopping-cart').push({
dateCreated: new Date().getTime()
});
}
async getCart(){
let cartId = await this.getOrCreateCartId();
return this.db.object('/shopping-cart/'+ cartId)
}

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

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


async addToCart(product: Product) {
let cartId = await this.getOrCreateCartId();
console.log(cartId)
//get reference of product ID insinde the cart
let item$= this.getItem(cartId, product.$key);
item$.take(1).subscribe(item => {
if (item.$exists()) item$.update({ quantity: item.quantity + 1 });
else item$.set({ product: product, quantity: 1 })

});
}

如果我只在点击事件上使用create方法,我不会收到任何错误,并且会创建带有日期时间的对象,但是在提交产品对象时,Angular会提示未定义的id...

编辑:关键字$exist和数量在下面一行

if (item.$exists()) item$.update({ quantity: item.quantity + 1 });

变得偏红,但VC没有代码建议

最佳答案

在您的代码中,您正在获取product,但随后您引用了this.product.$key。尝试使用 product.$key 来代替。

addToCart(product: Product){
this.cartService.addToCart(product);
console.log(this.shoppingCart)
let item = this.shoppingCart.item[product.$key];
console.log(item)
}

关于javascript - 错误类型错误 : Cannot read property '-LlWio7vFBuxfeviKdWa' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57358964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com