-
Notifications
You must be signed in to change notification settings - Fork 7
/
shopping-cart.service.ts
68 lines (58 loc) · 1.55 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
import { Injectable } from '@angular/core';
import { Item } from './item';
import { Subject, BehaviorSubject } from 'rxjs';
export interface CartEntry {
item: Item;
count: number;
}
const CART_KEY = "CART_KEY";
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
private entries: { [name: string]: CartEntry } = {};
/** Observable for current number of items in the cart */
onChanged: Subject<number>;
constructor() {
// Get the initial value from localStorage.
const storedValue = window.localStorage.getItem(CART_KEY);
if (storedValue) {
this.entries = JSON.parse(storedValue);
}
this.onChanged = new BehaviorSubject(this.getTotalCount());
}
private update() {
window.localStorage.setItem(CART_KEY, JSON.stringify(this.entries));
this.onChanged.next(this.getTotalCount());
}
/** Total count across all items */
getTotalCount() {
let count = 0;
for (const name in this.entries) {
count += this.entries[name].count;
}
return count;
}
/* Add a new instance of an item to the cart */
add(item: Item) {
const existing = this.entries[item.name];
if (existing) {
existing.count++;
} else {
this.entries[item.name] = { item, count: 1 };
}
this.update();
}
/* Get the current items */
getCartEntries() {
const result: CartEntry[] = [];
for (const name in this.entries) {
result.push(this.entries[name]);
}
return result;
}
delete(entry: CartEntry) {
delete this.entries[entry.item.name];
this.update();
}
}