1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {BehaviorSubject, firstValueFrom, Observable} from 'rxjs';
import {User} from '../models/User';
@Injectable({
providedIn: 'root'
})
export class UsersService {
private currentUser : BehaviorSubject<User | null> = new BehaviorSubject<User | null>(null);
private apiKey: string = "";
private url = "http://localhost:8080/users"
private authUrl = "http://localhost:8080/auth"
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
"jelly-api-key": this.apiKey
})
};
private 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
) {}
async createUser(username:string, password:string) {
await firstValueFrom(this.http.post<User>(this.url, {username: username, password: password}, this.httpOptions))
}
getUser(id: string): Observable<User> {
return this.http.get<User>(`${this.url}/${id}`, this.httpOptions)
}
updateUser(id: number): Observable<User> {
return this.http.put<User>(`${this.url}/${id}`, this.httpOptions)
}
deleteUser(id: number): Observable<boolean> {
return this.http.delete<boolean>(`${this.url}/${id}`, this.httpOptions)
}
getCurrentUserSubject() {
return this.currentUser;
}
getCurrentUser() {
return this.currentUser.getValue()
}
async login(username: string, password: string) {
let res = this.http.post<string>(this.authUrl, {username: username, password: password}, this.httpOptions2);
this.apiKey = await firstValueFrom(res);
console.log("apikey: "+this.apiKey)
let res2 = this.http.get<User>(`${this.url}/${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))
}
}
|