1
|
import {Injectable} from '@angular/core';
|
2
|
import {UserProfile} from '../../models/user.model';
|
3
|
import {Observable, of} from 'rxjs';
|
4
|
import {UsersService} from "../api/users.service";
|
5
|
|
6
|
@Injectable({
|
7
|
providedIn: 'root'
|
8
|
})
|
9
|
export class ProfileService {
|
10
|
private profile: UserProfile;
|
11
|
|
12
|
constructor(private usersService: UsersService) {
|
13
|
|
14
|
}
|
15
|
|
16
|
//hardcoded username for now, to be replaced after proper authentication is in place
|
17
|
public currentUserValue = "testuser@yoso.fi";
|
18
|
|
19
|
/**
|
20
|
* Returns logged user profile if the server responds
|
21
|
* with valid profile otherwise observer returns error
|
22
|
* with message 'Cannot log in'
|
23
|
*
|
24
|
* The idea was to cache the logged user profile but
|
25
|
* the changes to logged user would not be seen until
|
26
|
* the user logged off and then logged back in
|
27
|
*/
|
28
|
public getLoggedUser(cached?: boolean) {
|
29
|
if (cached && this.isUserLogged()) {
|
30
|
return of(this.profile);
|
31
|
}
|
32
|
|
33
|
return new Observable<UserProfile>((obs) => {
|
34
|
this.usersService.getLoggedUserProfile()
|
35
|
.subscribe((userProfile: UserProfile) => {
|
36
|
this.profile = {...userProfile};
|
37
|
obs.next(this.profile);
|
38
|
obs.complete();
|
39
|
},
|
40
|
error1 => {
|
41
|
obs.error(error1);
|
42
|
obs.complete();
|
43
|
});
|
44
|
});
|
45
|
}
|
46
|
|
47
|
/**
|
48
|
* Do not use at the start of the application
|
49
|
* User might be logged but the service hasn't
|
50
|
* finished the request for the user profile
|
51
|
*/
|
52
|
public isUserLogged(): boolean {
|
53
|
return this.profile == null;
|
54
|
}
|
55
|
|
56
|
public logUserOff(): void {
|
57
|
this.profile = null;
|
58
|
}
|
59
|
}
|