我正在尝试在Firebase中创建/更新购物车。我正在使用一项服务,该服务具有将localStorage ID添加到firebase的功能,并且如果该产品已经存在,它将在购物车中添加数量,否则会创建新产品。该错误发生在控制台 TypeError:无法读取null的属性“数量” ,并且在购物车服务中编译时也出现了错误。
shopping-cart.service.ts
import { take } from 'rxjs/operators';
import { AngularFireDatabase, snapshotChanges } from 'angularfire2/database';
import { Injectable } from '@angular/core';
import { Product } from './models/product';
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) { }
private create(){
console.log('shoping service')
return this.db.list('/shopping-carts').push({
dateCreated: new Date().getTime()
});
}
private getCart(cartId: string){
return this.db.object('/shoping-carts/'+ cartId);
}
private async getOrCreateCartId(){
let cartId = localStorage.getItem('cartId');
if(cartId) return cartId;
let result = await this.create();
localStorage.setItem('cartId', result.key);
return result.key;
}
private getItem(cartId: string, productId: string){
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId).valueChanges();
}
async addToCart(product: Product){
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.pipe(take(1)).subscribe( item => {
item$.update({ product: product, quantity: (item.quantity || 0) + 1});
});
}
shoppng-cart.service.ts(文档的相关部分)
private getItem(cartId: string, productId: string){
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId).valueChanges();
}
async addToCart(product: Product){
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.pipe(take(1)).subscribe( item => {
item$.update({ product: product, quantity: (item.quantity || 0) + 1});
});
}
product-card.component.ts
import { ShoppingCartService } from './../shopping-cart.service';
import { Product } from './../models/product';
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent implements OnInit {
@Input('product') product;
@Input('show-actions') showActions = true;
constructor(private cartService:ShoppingCartService) { }
addToCart(product:Product){
this.cartService.addToCart(product);
}
ngOnInit() {
}
}
product-card.component.html
<div *ngIf="product.title" class="card m-auto">
<img class="card-img-top" [src]="product.imageUrl" *ngIf="product.imageUrl" alt="{{ product.title }}">
<div class="card-body pb-0">
<h5 class="card-title">{{product.title}}</h5>
<p>{{product.price | currency: 'USD'}}</p>
</div>
<div class="card-footer p-0 border-top">
<button *ngIf="showActions" (click)="addToCart(product)" class="btn btn-primary btn-block">Add to Cart</button>
</div>
</div>
product.ts:
export interface Product{
key: string;
title: string;
price: number;
category: string;
imageUrl: string;
}
答案 0 :(得分:3)
错误描述性很强,可观察到,没有这样的属性。这是因为valueChanges()
函数返回一个observable,并且其中仅包含数据。但是AngularFireObject
具有更新功能,您需要使用它。因此,您需要修改代码,例如:
private getItem(cartId: string, productId: string): {
return this.db.object<any>('/shopping-carts/' + cartId + '/items/' + productId);
}
async addToCart(product: Product){
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.valueChanges().pipe(take(1)).subscribe((item: any) => {
item$.update({ product: product, quantity: (item.quantity || 0) + 1});
});
}
答案 1 :(得分:2)
经过大量搜索和调试后,Yevgen的一部分内容也得到了修改,以消除 ERROR TypeError:无法读取null的属性'quantity'。。如果我使用valueChanges
,则会在添加新购物车时出错。因此,我更改为snapshotChanges
并给出了它存在的逻辑并现在可以正常工作。如果仍然有人更新我的答案,我们将非常欢迎您。
private getItem(cartId:string, productId:string) {
return this.db.object < any > ('/shopping-carts/' + cartId + '/items/' + productId);
}
async addToCart(product:Product) {
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.snapshotChanges().pipe(take(1)).subscribe((item:any) => {
if (item.key != null) {
item$.update( {quantity:( item.payload.val().quantity || 0) + 1});
}
else{
item$.set( {product:product, quantity:1});
}
});
}