-
Notifications
You must be signed in to change notification settings - Fork 0
/
shopping-cart.service.ts
71 lines (56 loc) · 1.93 KB
/
shopping-cart.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Observable } from 'rxjs/Observable';
import { ShoppingCart } from './models/shopping-cart';
import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import { Product } from './models/product';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';
import { promise } from 'protractor';
@Injectable()
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) { }
async getCart(): Promise<Observable<ShoppingCart>>{
let cartId =await this.getOrCreateCartId();
return this.db.object('/shopping-carts/' + cartId)
.map(x => new ShoppingCart(x.items));
}
async addToCart(product: Product){
this.updateItem(product, 1);
}
async removeFromCart(product: Product){
this.updateItem(product,-1);
}
async clearCart(){
let cartId = await this.getOrCreateCartId();
this.db.object('/shopping-carts/' + cartId + '/items').remove();
}
private create(){
return this.db.list('/shopping-carts').push({
dateCtreted: new Date().getTime()
});
}
private getItem(cartId: string, productId: string){
return this.db.object('/shopping-carts/' + cartId + '/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;
}
private async updateItem(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
});
});
}
}