import {Injectable, Injector} from '@angular/core'; import {BehaviorSubject, firstValueFrom} from 'rxjs'; import {User} from '../models/User'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {UsersService} from './users.service'; @Injectable({ providedIn: 'root' }) export class AuthService { private authUrl = "http://localhost:8080/auth" private userUrl = "http://localhost:8080/users" private currentUser : BehaviorSubject = new BehaviorSubject(null); private apiKey: string = ""; httpOptions2 = () => ({ headers: new HttpHeaders({ 'Content-Type': 'application/json', "jelly-api-key": this.apiKey }), 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 userService: UsersService private injector: Injector ) {} async login(username: string, password: string) { let res = this.http.post(this.authUrl, {username: username, password: password}, this.httpOptions2()); this.apiKey = await firstValueFrom(res); console.log("apikey: "+this.apiKey) let res2 = this.http.get(`${this.userUrl}/${username}`, { headers: new HttpHeaders({ 'Content-Type': 'application/json', "jelly-api-key": this.apiKey }) }) let currentU = await firstValueFrom(res2); this.currentUser.next(currentU); // this.currentUser.subscribe(r => console.log("currentUser: "+r.username)) } async restoreLogin(username: string, key: string) { const userService = this.injector.get(UsersService); this.apiKey = key; this.currentUser.next(await firstValueFrom(userService.getUser(username))) } getCurrentUserSubject() { return this.currentUser; } getCurrentUser() { return this.currentUser.getValue() } getApiKey() { return this.apiKey; } }