javascript - 错误类型错误:无法读取未定义的属性“-LlWio7vFBuxfeviKdWa”
问题描述
将产品添加到最终托管在 Firebase 中的购物车时,我收到此错误。我正在关注本教程,但我似乎无法理解我所缺少的;该对象是在firebase中创建的,但错误仍然存在,我无法显示购物车中的产品数量......
产品组件的 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 没有代码建议
解决方案
在您的代码中,您正在接受 a 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)
}
推荐阅读
- symfony - 如何手动生成到easyadmin的路由
- python - 为什么我的 2 函数在第一个和第二个循环中没有被调用?
- javascript - 如何拆分数组并仅将特定值保存到数据库中?Laravel 与 Ajax
- php - 使用 PHP 进行会话验证
- python - 如何从文本文件中查找内容
- reactjs - Typescript React 道具类型有两种可能性
- javascript - 使用 android webview 时无法正确评估 Javascript 方括号表示法。有什么建议可以解决吗?
- java - 如何在 jpa 实体的属性上检索 DEFAULT CURRENT_TIMESTAMP 指定的最新(当前)时间值?
- firebase - 如何使用 url_launcher 包从 Cloud Firestore 添加 URL
- javascript - setInterval 使异步 ajax 函数停止工作