Internationalization not working on device (ionic cordova run android) but works on desktop (ionic serve)


#1

I am trying to implement Internationalization in my app. It works as required with ionic serve on desktop but fails on Android device after I run ionic cordova run android.

I get the following on Android device when I inspect it:

Failed to load resource: net::ERR_FILE_NOT_FOUND /android_asset/assets/i18n/en.json

Would appreciate if somebody can please help resolve it.

I have done following:

  1. Created en.json and other files in project_folder/src/assets/i18n folder.

  2. In app.module.ts file, added below lines:

import { TranslateModule, TranslateStaticLoader, TranslateLoader } from 'ng2-translate/ng2-translate';

export function createTranslateLoader(http: Http) {
	return new TranslateStaticLoader(http, '../assets/i18n', '.json');
}

@NgModule({
  declarations: [
    MyApp,
    .
    .
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (createTranslateLoader),
      deps: [Http]
    }),
    .
    .
    .
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    // all components
  ],
  providers: [
    .
    .
    .
  ]
})
  1. Then in my app.component.ts file, I have this:
    initializeApp() {
        this.platform.ready().then(() => {
            this.statusBar.styleDefault();
            this.splashScreen.hide();
            
            let userLang = navigator.language.split('-')[0];
            userLang = userLang.match(/cn|en|es|ja|it|ru/) ? userLang : 'en';
            this.translate.setDefaultLang('en');

            this.translate.use(userLang);
        });
    }
  1. And finally, in all my HTML files, I have the following to get the actual label value from correctly loaded language file.
{{'PAGE.label' | translate}}

As I said all this works fine with ionic serve command on desktop but it just prints the “{{‘PAGE.label’ | translate}}” as is on the UI when I try it on an Android device with ionic cordova run android command.

Any idea on what I might be missing?

Thanks.


#2

Maybe the path is not correct.

try ./assets/i18n/

hope it works.


#3

That was it! Thanks @fishi, appreciated!

Feel like stupid. That path is apparently relative to the compiled/transpiled code that goes in www folder. And I had it as per the src.


#4

Well I had the same issue some months ago :wink:

stupid is as stupid does

Forrest Gump