Catching a systems language on first app launch


#1

Hi everyone,

I want to set some default settings for my app. In doing so, I want to catch the systems language. I then export a function in the app.module.ts but it gives me a Cannot read property 'lang' of undefined

I am wondering, could it be that navigator is not available at this time when the code runs? Or is some async messing things up??

Here’s my code in app.module.ts so far:

export function provideSettings(storage: Storage) {
  // detect the system language of fall back to the default language for translation strings.
  let userLang = navigator.language.split("-")[0]; //use navigator lang if available
  userLang = /(nl|en)/gi.test(userLang) ? userLang : 'nl';
  
  return new Settings(storage, {
    lang: userLang,
    remindTime: "19:00",
    remindAgenda: false,
    remindNotify: false,
  });
}

#2

anyone has ideas how to do this?


#3

I don’t think you’re showing us where the error is spawning from, because I don’t see an attempt to access a property named ‘lang’ in the code you posted.


#4

Hi @rapropos! Thanks. The lang is read in app.component:

settings.load().then(() => {
  let allSettings = settings.allSettings;
  translate.setDefaultLang('nl');
  translate.use(allSettings.lang);
  console.log('User Lang: '+allSettings.lang);
})

For my app settings I am reusing the settings code from the Ionic Super starter. The load method is called from Settings provider.


#5

Others also suggested it’ll be good to detect a users language, here’s a pull request I used in my code: https://github.com/driftyco/ionic-starter-super/pull/53/files