Multi language support without plugin in ionic app

我只是一个虾纸丫 提交于 2019-12-13 03:38:44

问题


Following is my constant file in which I am setting language of ionic app.

@Injectable()
export class Constant {
  public static selectedLang :string = 'EN';

  static setLanguage(languageCode : string){
    Constant.selectedLang = languageCode;

  }
  readonly data: any = {
    "EN": {
      //declared English variables used to be all over the application
             FORGOT_PASSWORD : "Forgot Password",
          }
    "MR": {
             //marathi variables
             FORGOT_PASSWORD : "पासवर्ड विसरलात",
           }
    "HI":{
             //Hindi variables
             FORGOT_PASSWORD : "पासवर्ड भूल गए",
         }
   LANG: any = this.data[Constant.selectedLang];
 }

I use this variables in HTML in following way:

<div>
   <h2>{{CON.LANG.FORGOT_PASSWORD}}</h2>
   <p>{{CON.LANG.FORGOT_PASSWORD}}</p>
</div>

ts file where I set language:

import {Constant} from "../../../../constants";
class ForgotPassword {
    constructor(public CON: Constant){}

    setLanguage(languageCode : string){
       Constant.setLanguage(languageCode);
    }
 }

Here, I want to keep English as my default language. When user explicitly changes the language by calling the function, then only language should be changed. But the issue is Even if user calls the function to change language, its not changed. App is always showing English variables.

Your help is appreciated.


回答1:


I have got what I was doing wrong earlier. I made 'data' and 'LANG' variables of Constant file normal instead of static. And changed the setLanguage function as follows.

 setLanguage(languageCode : string){
    this.selectedLang = languageCode;
    this.LANG = this.data[this.selectedLang]; //line added
  }

Also, I stored my selectedLanguage variable from component to session storage so that, language will not be changed after I close and open the app again.

 setLanguage(languageCode : string){
    this.CON.setLanguage(languageCode);
    this.sessionProvider.setLanguage(languageCode);
  }


来源:https://stackoverflow.com/questions/52159180/multi-language-support-without-plugin-in-ionic-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!