import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, catchError, EMPTY, Observable, tap } from 'rxjs'; import { User } from '../model/User'; import { environment } from '@environments/environment'; @Injectable({ providedIn: 'root', }) export class UserService { private apiUrl = `${environment.apiUrl}/api/users`; private currentUserSubject = new BehaviorSubject(null); constructor(private http: HttpClient) {} public getUserById(id: number): Observable { return this.http.get(`${this.apiUrl}/${id}`); } public getUserByUsername(username: string): Observable { return this.http.get(`${this.apiUrl}/username/${username}`); } public getCurrentUser(): Observable { return this.http.get('/backend/user').pipe( catchError(() => EMPTY), tap((user) => this.currentUserSubject.next(user)) ); } public refreshCurrentUser(): void { this.getCurrentUser().subscribe(); } public updateLocalBalance(amount: number): void { const currentUser = this.currentUserSubject.getValue(); if (currentUser) { const updatedUser = { ...currentUser, balance: currentUser.balance + amount, }; this.currentUserSubject.next(updatedUser); } } public createUser(id: string, username: string): Observable { return this.http .post('/backend/user', { authentikId: id, username: username, }) .pipe(tap((user) => this.currentUserSubject.next(user))); } }