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