CartService und Buy-Button auf Detail-Seite hinzugefĆ¼gt
authorKai Moritz <kai@juplo.de>
Sat, 21 Dec 2019 11:35:41 +0000 (12:35 +0100)
committerKai Moritz <kai@juplo.de>
Sat, 21 Dec 2019 11:35:41 +0000 (12:35 +0100)
src/app/cart.service.spec.ts [new file with mode: 0644]
src/app/cart.service.ts [new file with mode: 0644]
src/app/product-details/product-details.component.html
src/app/product-details/product-details.component.ts

diff --git a/src/app/cart.service.spec.ts b/src/app/cart.service.spec.ts
new file mode 100644 (file)
index 0000000..a686b44
--- /dev/null
@@ -0,0 +1,12 @@
+import { TestBed } from '@angular/core/testing';
+
+import { CartService } from './cart.service';
+
+describe('CartService', () => {
+  beforeEach(() => TestBed.configureTestingModule({}));
+
+  it('should be created', () => {
+    const service: CartService = TestBed.get(CartService);
+    expect(service).toBeTruthy();
+  });
+});
diff --git a/src/app/cart.service.ts b/src/app/cart.service.ts
new file mode 100644 (file)
index 0000000..aeb5d9e
--- /dev/null
@@ -0,0 +1,24 @@
+import { Injectable } from '@angular/core';
+
+@Injectable({
+  providedIn: 'root'
+})
+export class CartService {
+
+  items= [];
+
+  constructor() { }
+
+  addToCart(product) {
+    this.items.push(product);
+  }
+
+  getItems() {
+    return this.items;
+  }
+
+  clearCart() {
+    this.items = [];
+    return this.items;
+  }
+}
index a86d6b8..726bc78 100644 (file)
@@ -4,4 +4,5 @@
   <h3>{{ product.name }}</h3>
   <h4>{{ product.price | currency }}</h4>
   <p>{{ product.description }}</p>
+  <button (click)="addToCart(product)">Buy</button>
 </div>
index 049b7cc..c6067b1 100644 (file)
@@ -1,6 +1,7 @@
 import { Component, OnInit } from '@angular/core';
 import { ActivatedRoute } from '@angular/router';
 import { products } from '../products';
+import { CartService } from '../cart.service';
 
 @Component({
   selector: 'app-product-details',
@@ -10,7 +11,9 @@ import { products } from '../products';
 export class ProductDetailsComponent implements OnInit {
   product;
 
-  constructor(private route: ActivatedRoute) { }
+  constructor(
+      private route: ActivatedRoute,
+      private cartService: CartService) { }
 
   ngOnInit() {
     this.route.paramMap.subscribe(params => {
@@ -18,4 +21,7 @@ export class ProductDetailsComponent implements OnInit {
     });
   }
 
+  addToCart(product) {
+    this.cartService.addToCart(product);
+  }
 }