import { Injectable , OnInit } from '@angular/core' ; import { TranslateService as NGXTranslateService } from '@ngx-translate/core' ; import { UserService } from './user.service' ; import { User } from '../models/user' ; const langs = [ 'en' , 'fr' , 'ru' , 'he' , 'zh' , 'pt' , 'it' ] ; const langmatch = /en|fr|ru|he|zh|pt|it/ ; @ Injectable ( ) export class TranslateService implements OnInit { private lang = 'us' ; private currentUser : User ; constructor ( private userServ , private translate ) { translate . addLangs ( langs ) ; translate . setDefaultLang ( 'en' ) ; this . userServ . getCurrent ( ) . subscribe ( ( user ) => { this . currentUser = user ; const browserLang = this . translate . getBrowserLang ( ) ; const browserCultureLang = this . translate . getBrowserCultureLang ( ) ; console . log ( 'Detected browser language: "' + browserCultureLang + '"' ) ; let useLang = 'en' ; const prefLang = ( this . currentUser ) ? this . currentUser . preferredLang : null ; if ( ! prefLang ) { useLang = browserLang . match ( langmatch ) ? browserLang : 'en' ; } else { console . log ( 'Detected User preferred language: "' + prefLang + '"' ) ; useLang = prefLang . match ( langmatch ) ? prefLang : 'en' ; } this . translate . use ( useLang ) ; console . log ( 'Translation language has been set to: "' + useLang + '"' ) ; } ) ; } public ngOnInit ( ) { } public getTranslate ( ) { return this . translate ; } }