moya-locale.service.ts
1.89 KB
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
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {MoyaLocale} from './moya-locale.model';
import {MOYA_BASE_URL, MoyaRestTool} from '../../shared/tools/moya-rest.tool';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/catch';
export const DEFAULT_LOCALE = 'fi';
const LOCALSTORAGE_NAME = 'currently used locale code';
@Injectable()
export class MoyaLocaleService {
constructor(private http: HttpClient) { }
/**
* Order of Locale:
* 1. User's locale from database
* 2. User's locale from cookie
* 3. Event's locale from database
* 4. Default
*
* @return {Observable<string>} Return current locale as a string. No errors.
*/
public getUserLocale(): Observable<string> {
return this.http.get<MoyaLocale>(MOYA_BASE_URL + '/v3/locale/').catch(x => Observable.of(new MoyaLocale())).map(locale => {
if (locale && locale.userLocale) {
return locale.userLocale;
}
const storageLocale = localStorage.getItem(LOCALSTORAGE_NAME);
if (storageLocale) {
return storageLocale;
}
if (locale.eventLocale) {
return locale.eventLocale;
}
return DEFAULT_LOCALE;
});
}
/**
* Store user's locale. This will store it to server. Or server is not available, into localstorage.
*
* There is no errors
* @param {string} locale
* @return {Promise<any>} This will return promise, but it will contain nothing.
*/
public setUserLocale(locale: string): void {
const newLocale: MoyaLocale = new MoyaLocale();
newLocale.userLocale = locale;
// let's save locale to database, if it fails, we save it into localstorage. No errors to show for user.
this.http.post(MOYA_BASE_URL + '/v3/locale/', newLocale).first().catch(x => {
localStorage.setItem(LOCALSTORAGE_NAME, locale);
return 'ok';
}).subscribe();
}
}