1 import {Injectable} from '@angular/core';
2 import {Location} from '@angular/common';
3 import {environment} from '../../environments/environment';
4 import {Observable} from 'rxjs/Observable';
5 import {of} from 'rxjs';
6 import {CookieService} from 'ngx-cookie';
7 import {IdlObject} from '@eg/core/idl.service';
8 import {PcrudService} from '@eg/core/pcrud.service';
10 @Injectable({providedIn: 'root'})
11 export class LocaleService {
14 private ngLocation: Location,
15 private cookieService: CookieService,
16 private pcrud: PcrudService) {
19 setLocale(code: string) {
20 let url = this.ngLocation.prepareExternalUrl('/');
22 // The last part of the base path will be the locale
23 // Replace it with the selected locale
24 url = url.replace(/\/[a-z]{2}-[A-Z]{2}\/$/, `/${code}`);
26 // Finally tack the path of the current page back onto the URL
27 // which is more friendly than forcing them back to the splash page.
28 url += this.ngLocation.path();
30 // Set a 10-year locale cookie to maintain compatibility
31 // with the AngularJS client.
32 // Cookie takes the form aa_bb instead of aa-BB
33 const cookie = code.replace(/-/, '_').toLowerCase();
34 this.cookieService.put('eg_locale',
35 cookie, {path : '/', secure: true, expires: '+10y'});
37 window.location.href = url;
40 // Returns codes supported for the current environment.
41 supportedLocaleCodes(): string[] {
42 return environment.locales || [];
45 // Returns i18n_l objects matching the locales supported
46 // in the current environment.
47 supportedLocales(): Observable<IdlObject> {
48 const locales = this.supportedLocaleCodes();
50 if (locales.length === 0) {
54 return this.pcrud.search('i18n_l', {code: locales});
57 // Extract the local from the URL.
58 // It's the last component of the base path.
59 // Note we don't extract it from the cookie since using cookies
60 // to store the locale will not be necessary when AngularJS
62 currentLocaleCode(): string {
63 const base = this.ngLocation.prepareExternalUrl('/');
64 const code = base.match(/\/([a-z]{2}-[A-Z]{2})\/$/);
65 return code ? code[1] : '';