moya-locale.service.ts
1.79 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
import { Injectable } from '@angular/core';
import {MoyaRestService} from "../../shared/services/moya-rest.service";
import {Observable} from "rxjs/Observable";
import {MoyaLocale} from "./moya-locale.model";
export const DEFAULT_LOCALE = "fi";
const LOCALSTORAGE_NAME = "currently used locale code";
@Injectable()
export class MoyaLocaleService {
constructor(private moyaRest : MoyaRestService) { }
/**
* 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.moyaRest.get("/v3/locale/").catch(x => null ).map(untypedLocale => {
const locale = untypedLocale as MoyaLocale;
if (locale.userLocale) {
return locale.userLocale;
}
let cookieLocale = localStorage.getItem(LOCALSTORAGE_NAME);
if(cookieLocale) {
return cookieLocale;
}
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): Observable<any> {
let 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.
return this.moyaRest.post("/v3/locale/", newLocale).first().catch(x => {
localStorage.setItem(LOCALSTORAGE_NAME, locale);
return "ok";
});
}
}