--- /dev/null
+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();
+ });
+});
--- /dev/null
+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;
+ }
+}
<h3>{{ product.name }}</h3>
<h4>{{ product.price | currency }}</h4>
<p>{{ product.description }}</p>
+ <button (click)="addToCart(product)">Buy</button>
</div>
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',
export class ProductDetailsComponent implements OnInit {
product;
- constructor(private route: ActivatedRoute) { }
+ constructor(
+ private route: ActivatedRoute,
+ private cartService: CartService) { }
ngOnInit() {
this.route.paramMap.subscribe(params => {
});
}
+ addToCart(product) {
+ this.cartService.addToCart(product);
+ }
}