Projekt

Obecné

Profil

Stáhnout (1.24 KB) Statistiky
| Větev: | Tag: | Revize:
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 {AuthService} from '../services/auth.service';
5
import {LoginService} from '../../shared/api/endpoints/services/login.service';
6 b5525aef hlavja
import {ToastService} from '../../shared/services/toast.service';
7 f8b9a3a2 hlavja
8
@Injectable({
9
  providedIn: 'root'
10
})
11
export class UserState {
12 2c5da396 hlavja
  private userState$: BehaviorSubject<User> = new BehaviorSubject<User>(null);
13 f8b9a3a2 hlavja
14 87c1bdd1 hlavja
  constructor(
15 b5525aef hlavja
    private loginService: LoginService,
16
    private toastService: ToastService
17 87c1bdd1 hlavja
  ) {}
18 f8b9a3a2 hlavja
19 2c5da396 hlavja
  setUser(user: User): void {
20 f8b9a3a2 hlavja
    this.userState$.next(user);
21
  }
22
23 2c5da396 hlavja
  setLoggedIn(loggedIn: boolean) {
24
    this.userState$.next({...this.userState$.getValue(), isLoggedIn: loggedIn})
25 f8b9a3a2 hlavja
  }
26
27 2c5da396 hlavja
  getUser(): User {
28
    return this.userState$.getValue();
29 f8b9a3a2 hlavja
  }
30
31 2c5da396 hlavja
  getUser$(refresh: boolean = false): Observable<User> {
32 87c1bdd1 hlavja
   if (this.userState$.getValue()){
33 b5525aef hlavja
      this.loginService.getUserInfo$Response().subscribe(res => {
34
        this.userState$.next({...this.userState$.getValue(), userInfo: res.body});
35
      }, err => this.toastService.showError(err.error.message));
36
   }
37 2c5da396 hlavja
    return this.userState$.asObservable();
38 f8b9a3a2 hlavja
  }
39
40
  getLoggedIn(): boolean {
41 2c5da396 hlavja
    return this.userState$.getValue().isLoggedIn;
42 2ddd52c9 hlavja
  }
43 f8b9a3a2 hlavja
}