Skip to content

Commit

Permalink
Clear the shopping cart.
Browse files Browse the repository at this point in the history
  • Loading branch information
mosh-hamedani committed Aug 24, 2017
1 parent ff34aa0 commit 894caee
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/app/shopping-cart.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,32 @@ 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));
}

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({
dateCreated: new Date().getTime()
});
}

private getItem(cartId: string, productId: string) {
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}
Expand All @@ -36,14 +50,6 @@ export class ShoppingCartService {
return result.key;
}

async addToCart(product: Product) {
this.updateItem(product, 1);
}

async removeFromCart(product: Product) {
this.updateItem(product, -1);
}

private async updateItem(product: Product, change: number) {
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.$key);
Expand Down
3 changes: 3 additions & 0 deletions src/app/shopping-cart/shopping-cart.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,7 @@ <h1>Shopping Cart</h1>
</tr>
</tfoot>
</table>
<button
(click)="clearCart()"
class="btn btn-danger btn-sm">Clear Shopping Cart</button>
</ng-container>
4 changes: 4 additions & 0 deletions src/app/shopping-cart/shopping-cart.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ export class ShoppingCartComponent implements OnInit {
async ngOnInit() {
this.cart$ = await this.shoppingCartService.getCart();
}

clearCart() {
this.shoppingCartService.clearCart();
}
}

0 comments on commit 894caee

Please sign in to comment.