我有一个角度项目,我有两个组件。 导航栏组件和产品组件。 他们都叫服务买车。该服务将cartId变量存储在本地存储中,用于访问购物车。
第二次在第二个组件中调用getOrCreateCartId函数时,能够从localstorage中读取项目似乎存在问题。
服务如下:
import { ShoppingCart } from './models/shopping-cart';
import { Product } from './models/product';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ShoppingCartService {
constructor(private db:AngularFireDatabase) { }
private create(){
return this.db.list('/shopping-carts').push({
dateCreated:new Date().getTime()
})
}
async getCart() : Promise<Observable<ShoppingCart>> {
let cartId = await this.getOrCreateCartId();
return this.db.object('/shopping-carts/'+cartId)
.map(x=>new ShoppingCart(x.items));
}
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;
}
private getItem(cartId:string, productId:string){
return this.db.object('/shopping-carts/'+cartId+'/items/'+productId);
}
addToCart(product:Product){
this.updateItemQuantity(product,1);
}
removeFromCart(product:Product){
this.updateItemQuantity(product,-1);
}
private async updateItemQuantity(product: Product, change: number) {
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.$key);
item$.take(1).subscribe(item => {
let quantity = (item.quantity || 0) + change;
if (quantity === 0) item$.remove();
else item$.update({
title: product.title,
imageUrl: product.imageUrl,
price: product.price,
quantity: quantity
});
});
}
async clearCart(){
let cartId = await this.getOrCreateCartId();
this.db.object('/shopping-carts/'+cartId+'/items').remove();
}
}
我遇到的问题是导航栏第一次设置购物车对象(这是假设初始运行,浏览器在本地存储中已经没有cartId)
然后,当产品组件调用getCart()时,它似乎无法读取let cartId = localStorage.getItem('cartId');
相反,它也创造了另一个购物车。
答案 0 :(得分:2)
You get it with await so app goes ahead and then when it does promise, a card is set but probably in your case, it's too late and that's why it creates a new card.
答案 1 :(得分:0)
let cartId = JSON.parse(localStorage.getItem('cartId')).cardId;