我在这里解决了一些问题,但是得到了以下消息:
Reference.update失败:第一个参数包含未定义的属性'购物车。-LRvqLfzwv9q9OMfW23K.items.-LPa0C_lNj2VAe1xLF5S.product.title'
未创建根。
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) { }
private create() {
return this.db.list('/shopping-carts').push({
dateCreated: new Date().getTime()
});
}
private getCart(cartId: string) {
return this.db.object('/shopping-carts/' + cartId);
}
getItem(cartId: string, productId: string) {
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}
private async getOrCreateCartId() {
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) {
const cartId = await this.getOrCreateCartId();
const item$ = this.getItem(cartId, product.key);
item$.snapshotChanges().take(1).subscribe((item: any) => {
if (item.payload.exists()) {
item$.update({ product: product, quantity: item.payload.val().quantity + 1});
} else {
item$.update({ product: {
title: product.title,
price: product.price,
category: product.category,
imageUrl: product.imageUrl,
}, quantity: 1} );
}
});
}
答案 0 :(得分:0)
尝试更改此行:
item $ .update({product:product,quanity:(item.payload.val.quanity + 1})
与
item $ .update({product:product,quanity:(item.payload.val.quanity + 1)})
更新对象时,您缺少')'。
答案 1 :(得分:0)
最后,我解决了这个问题,我想与所有人共享
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) { }
private create() {
return this.db.list('/shopping-carts').push({
dateCreated: new Date().getTime()
});
}
private getCart(cartId: string) {
return this.db.object('/shopping-carts/' + cartId);
}
getItem(cartId: string, productId: string) {
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}
private async getOrCreateCartId() {
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) {
const cartId = await this.getOrCreateCartId();
const item$ = this.getItem(cartId, product.key);
console.log(item$);
item$.snapshotChanges().take(1).subscribe((item: any) => {
if (item.payload.exists()) {
item$.update({quantity: item.payload.val().quantity + 1 });
} else {
item$.update({
product: {
title: product.payload.val().title,
price: product.payload.val().price,
category: product.payload.val().category,
imageUrl: product.payload.val().imageUrl,
}, quantity: 1
});
}
});
}
}