import { Injectable , ApplicationRef } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Subject } from 'rxjs' ; import { constants } from '../../../constants' ; import { StoreService } from 'app/store/store.service' ; import { Settings } from 'app/settings' ; export interface Language { name : string ; code : string ; } @ Injectable ( { providedIn : 'root' } ) export class I18nService { public state ; public data : { } ; public currentLanguage : Language = { name : 'default' , code : 'en' } ; constructor ( private http , private ref , private storeService ) { this . state = new Subject ( ) ; this . storeService . ready . subscribe ( async ( ready ) => { if ( ! ready ) { return ; } const { language } = await this . storeService . getSettings ( ) ; this . initLanguage ( language ) ; } ) ; } private fetch ( locale ) { this . http . get ( `locales/${ locale }.json` ) . subscribe ( ( data ) => { this . data = data ; this . state . next ( data ) ; } ) ; } private initLanguage ( locale ) { const language = constants . languages . find ( it => it . code === locale ) ; if ( language ) { this . setLanguage ( language ) ; } else { throw new Error ( `Incorrect locale used for I18nService: ${ locale }` ) ; } } async setLanguage ( language ) { this . currentLanguage = language ; const settings = await this . storeService . getSettings ( ) ; settings . language = language . code ; await this . storeService . saveSettings ( settings ) ; this . fetch ( language . code ) ; } subscribe ( sub , err ) { return this . state . subscribe ( sub , err ) ; } public getTranslation ( phrase , opts ? ) { return this . data && this . data [ phrase ] ? this . data [ phrase ] : phrase ; } }