@@ -40,24 +40,56 @@ export class NgxI18nRootService {
4040 * @param language - The provided language
4141 */
4242 public setCurrentLanguage ( language : string ) : void {
43- // Iben: If a language is set that's not part of the available languages, we return a warn
43+ // Iben: Save the new language
44+ let newLanguage = language ;
45+
46+ // Iben: Check if the new language is part of the available languages
4447 if ( ! this . configuration . availableLanguages . includes ( language ) ) {
48+ // Iben: If a language is set that's not part of the available languages, we return a warn
4549 console . warn (
4650 `NgxI18n: A language, ${ language } , was attempted to be set that was not part of the available languages (${ this . configuration . availableLanguages . join (
4751 ', '
4852 ) } )`
4953 ) ;
5054
51- // Iben: Early exit
52- return ;
55+ // Iben: If there is already a language set, we early exit and keep the remaining language
56+ if ( this . currentLanguage ) {
57+ return ;
58+ }
59+
60+ // Iben: If no language exists, we use the default language
61+ newLanguage = this . configuration . defaultLanguage ;
5362 }
5463
5564 // Iben: Save the current language to the localStorage when we're in the browser
5665 if ( isPlatformBrowser ( this . platformId ) ) {
57- localStorage . setItem ( 'ngx-language' , language ) ;
66+ localStorage . setItem ( 'ngx-i18n- language' , newLanguage ) ;
5867 }
5968
6069 // Iben: Update the subject
61- this . currentLanguageSubject . next ( language ) ;
70+ this . currentLanguageSubject . next ( newLanguage ) ;
71+ }
72+
73+ /**
74+ * Sets the initial language of the application when no language is set yet.
75+ *
76+ * If a previous language was set in the local storage, said language is used. If not, the default language gets used.
77+ */
78+ public initializeLanguage ( ) : void {
79+ // Iben: If the current language already exists, we early exit
80+ if ( this . currentLanguage ) {
81+ return ;
82+ }
83+
84+ // Iben: If the current language does not exist, we check if it exists in the local storage, if not, we use the default config
85+ let language = this . configuration . defaultLanguage ;
86+
87+ if ( isPlatformBrowser ( this . platformId ) ) {
88+ language =
89+ localStorage . getItem ( 'ngx-i18n-language' ) || this . configuration . defaultLanguage ;
90+ }
91+
92+ // Iben: We set the new language
93+ this . setCurrentLanguage ( language ) ;
6294 }
6395}
0 commit comments