feat: added services, model and environment
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
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)
|
||||
);
|
||||
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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user