import { Injectable, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs'; import { AddCartRequest, AddCartResponse } from '../models/product.model'; import { environment } from '../../../environments/environment'; const API_BASE_URL = environment.apiBaseUrl; const CART_COUNT_STORAGE_KEY = environment.cartCountStorageKey; // Add cart implementation (just for visualization, not used in the app) @Injectable({ providedIn: 'root' }) export class CartService { private readonly http = inject(HttpClient); //total items on cart readonly count = signal(this.readPersistedCount()); async addToCart(request: AddCartRequest): Promise { const response = await firstValueFrom( this.http.post(`${API_BASE_URL}/cart`, request) ); //Note: can return always 1 because server has not SameSite=None. This will be taken as a third cookie, and the browser can ignore it. this.setCount(response.count); return response.count; } // reloads counter from localstorage private readPersistedCount(): number { const raw = localStorage.getItem(CART_COUNT_STORAGE_KEY); const parsed = raw ? Number(raw) : 0; return Number.isFinite(parsed) ? parsed : 0; } private setCount(count: number): void { this.count.set(count); localStorage.setItem(CART_COUNT_STORAGE_KEY, String(count)); } }