1 |
f8b9a3a2
|
hlavja
|
import {Injectable} from '@angular/core';
|
2 |
|
|
import {BehaviorSubject, Observable} from 'rxjs';
|
3 |
2c5da396
|
hlavja
|
import {User} from '../models/user';
|
4 |
87c1bdd1
|
hlavja
|
import {LoginService} from '../../shared/api/endpoints/services/login.service';
|
5 |
b5525aef
|
hlavja
|
import {ToastService} from '../../shared/services/toast.service';
|
6 |
f8b9a3a2
|
hlavja
|
|
7 |
|
|
@Injectable({
|
8 |
|
|
providedIn: 'root'
|
9 |
|
|
})
|
10 |
|
|
export class UserState {
|
11 |
2c5da396
|
hlavja
|
private userState$: BehaviorSubject<User> = new BehaviorSubject<User>(null);
|
12 |
f8b9a3a2
|
hlavja
|
|
13 |
87c1bdd1
|
hlavja
|
constructor(
|
14 |
b5525aef
|
hlavja
|
private loginService: LoginService,
|
15 |
|
|
private toastService: ToastService
|
16 |
87c1bdd1
|
hlavja
|
) {}
|
17 |
f8b9a3a2
|
hlavja
|
|
18 |
2c5da396
|
hlavja
|
setUser(user: User): void {
|
19 |
f8b9a3a2
|
hlavja
|
this.userState$.next(user);
|
20 |
|
|
}
|
21 |
|
|
|
22 |
2c5da396
|
hlavja
|
setLoggedIn(loggedIn: boolean) {
|
23 |
|
|
this.userState$.next({...this.userState$.getValue(), isLoggedIn: loggedIn})
|
24 |
f8b9a3a2
|
hlavja
|
}
|
25 |
|
|
|
26 |
2c5da396
|
hlavja
|
getUser(): User {
|
27 |
|
|
return this.userState$.getValue();
|
28 |
f8b9a3a2
|
hlavja
|
}
|
29 |
|
|
|
30 |
cbb91c90
|
hlavja
|
/**
|
31 |
|
|
* Get user, if not exists fetch from server
|
32 |
|
|
* @param refresh force refresh user status from backend
|
33 |
|
|
*/
|
34 |
2c5da396
|
hlavja
|
getUser$(refresh: boolean = false): Observable<User> {
|
35 |
87c1bdd1
|
hlavja
|
if (this.userState$.getValue()){
|
36 |
b5525aef
|
hlavja
|
this.loginService.getUserInfo$Response().subscribe(res => {
|
37 |
|
|
this.userState$.next({...this.userState$.getValue(), userInfo: res.body});
|
38 |
|
|
}, err => this.toastService.showError(err.error.message));
|
39 |
|
|
}
|
40 |
2c5da396
|
hlavja
|
return this.userState$.asObservable();
|
41 |
f8b9a3a2
|
hlavja
|
}
|
42 |
|
|
|
43 |
|
|
getLoggedIn(): boolean {
|
44 |
2c5da396
|
hlavja
|
return this.userState$.getValue().isLoggedIn;
|
45 |
2ddd52c9
|
hlavja
|
}
|
46 |
f8b9a3a2
|
hlavja
|
}
|