import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {BehaviorSubject, catchError, firstValueFrom, Observable, of} from 'rxjs'; import {User} from '../models/User'; import { Need } from '../models/Need'; import { CupboardService } from './cupboard.service'; import {AuthService} from './auth.service'; @Injectable({ providedIn: 'root' }) export class UsersService { private basket = new BehaviorSubject([]); private url = "http://localhost:8080/users" httpOptions = () => ({ headers: new HttpHeaders({ 'Content-Type': 'application/json', "jelly-api-key": this.authService.getApiKey() }) }); httpOptions2 = () => ({ headers: new HttpHeaders({ 'Content-Type': 'application/json', "jelly-api-key": this.authService.getApiKey() }), responseType: "text" as "json" // don't ask me how or why this works, bc i have no clue... // see the relevant angular bug report https://github.com/angular/angular/issues/18586 }); constructor( private http: HttpClient, private cupboardService: CupboardService, private authService: AuthService ) {} async createUser(username:string, password:string) { await firstValueFrom(this.http.post(this.url, {username: username, password: password}, this.httpOptions())) } getUser(id: string): Observable { return this.http.get(`${this.url}/${id}`, this.httpOptions()) } getCount(): Observable { return this.http.get(`${this.url}/count`, this.httpOptions2()) } updateUser(user: User): Observable { console.log(`${this.url}/${user.username}`, user, this.httpOptions) return this.http.put(`${this.url}/${user.username}`, user, this.httpOptions()) } deleteUser(id: number): Observable { return this.http.delete(`${this.url}/${id}`, this.httpOptions()) } refreshBasket() { let promiseArr = this.authService.getCurrentUser()!.basket.map(async needID => { return await firstValueFrom(this.cupboardService.getNeed(needID)); }) Promise.all(promiseArr).then(r => this.basket.next(r)); } removeNeed(id: number) { let newArr = this.basket.getValue().filter(v => v.id != id); this.basket.next(newArr); this.authService.getCurrentUser()!.basket = newArr.map(need => need.id); this.updateUser(this.authService.getCurrentUser()!) .pipe( catchError((err: any, _) => { console.error(err); return of(); }) ) .subscribe(() => { this.refreshBasket(); }); } getBasket() { return this.basket; } }