2026-07-12 18:00:49 +02:00
|
|
|
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<number>(this.readPersistedCount());
|
|
|
|
|
|
|
|
|
|
async addToCart(request: AddCartRequest): Promise<number> {
|
|
|
|
|
const response = await firstValueFrom(
|
|
|
|
|
this.http.post<AddCartResponse>(`${API_BASE_URL}/cart`, request)
|
|
|
|
|
);
|
2026-07-12 19:27:27 +02:00
|
|
|
|
|
|
|
|
//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.
|
2026-07-12 18:00:49 +02:00
|
|
|
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));
|
|
|
|
|
}
|
|
|
|
|
}
|