import { HttpClient, HttpErrorResponse } from "@angular/common/http"; import { effect, inject, Injectable } from "@angular/core"; import { API_URL } from "../tokens/api-url-tokens"; import { CartItemRequest, CartModel } from "../models/cart.model"; import { AuthService } from "@core/services/auth-service"; import { BehaviorSubject, tap } from "rxjs"; @Injectable({ providedIn: "root", }) export class CartService { private authService = inject(AuthService); // dependencies private http = inject(HttpClient); private apiUrl = inject(API_URL); private _cartItems = new BehaviorSubject({} as CartModel); cartItems$ = this._cartItems.asObservable(); constructor() { effect(() => { if (this.authService.isAuthenticated()) { this.fetchCart(); } else { this._cartItems.next({} as CartModel); } }); } fetchCart() { return this.http.get(this.apiUrl + "/cart").subscribe({ next: (data) => this._cartItems.next(data), error: (error: HttpErrorResponse) => { if (error.status === 401) { this.authService.purgeAuth(); } // show an error in toast }, }); } addToCart(data: CartItemRequest) { return this.http .post(this.apiUrl + "/cart", data) .pipe(tap((updatedCart: CartModel) => this._cartItems.next(updatedCart))); } updateCart(data: CartItemRequest) { return this.http .patch(this.apiUrl + "/cart", data) .pipe(tap((updatedCart: CartModel) => this._cartItems.next(updatedCart))); } removeFromCart(productId: number) { return this.http .delete(this.apiUrl + "/cart", { body: { productId: productId } }) .pipe(tap((updatedCart: CartModel) => this._cartItems.next(updatedCart))); } }