[英]ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined
I'm a beginner to Angular.我是 Angular 的初学者。 I'm watching the tutorial of Mosh Hamedani which is in angular version 4 but I am using higher version.
我正在观看 angular 版本 4 中的 Mosh Hamedani 教程,但我使用的是更高版本。 I'm working on the e-commerce project on AddToCart button where the product should increase it's quantity by clicking the button and updated in Firebase using productId and also if I try to add new product then id of that new product should add in AngularFire Database.
我正在处理 AddToCart 按钮上的电子商务项目,其中产品应该通过单击按钮来增加数量并使用 productId 在 Firebase 中更新,如果我尝试添加新产品,那么该新产品的 id 应该添加到 AngularFire 数据库中.
Everything is working perfectly now I'm getting error in shopping-cart.service.ts file.现在一切正常,我在 shopping-cart.service.ts 文件中遇到错误。 I am getting this error in the console while trying to add a product to cart ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined.
我在尝试将产品添加到购物车时在控制台中收到此错误错误错误:未捕获(承诺):类型错误:无法读取未定义的属性“key”。 I error is in line product.key Here is the code.
我的错误是在 line product.key 这是代码。
product.ts产品.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private db : AngularFireDatabase) { }
create(product){
return this.db.list('/products').push(product);
}
getAll(){
return this.db.list('/products').snapshotChanges().pipe(
map((products:any[])=>products.map(prod=>{
const payload = prod.payload.val();
const key = prod.key;
return <any>{key,...payload};
}))
)
}
get(productId){
return this.db.object('/products'+productId).valueChanges();
}
delete(productId){
return this.db.object('/products'+productId).remove();
}
}
shopping-cart.service.ts购物车.service.ts
async addToCart(product:Product){
let cartId = await this.getOrCreateCartId();
let item$:Observable<any> = this.db.object('/shopping-cart/' + cartId + '/items/' + product.key).valueChanges();
let item$$ = this.db.object('/shopping-carts/' + cartId + '/items/' + product.key);
item$.pipe(take(1)).subscribe(item=>{
if(item===null){
item$$.set({product:product,quantity:1});
console.log("Adding new product to cart");
}else{
item$$.update({quantity:item.quantity+1});
console.log("Updating the quantity")
}
});
}
product.ts产品.ts
export interface Product{
key:string;
title:string;
price:number;
category:string;
imageUrl:string;
}
很可能您的 item$ 在您执行 item$.pipe(take(1)) 时未初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.