Angular 5 internationalization

前端 未结 3 2081
感情败类
感情败类 2020-12-04 19:16

I\'m building an application using the latest Angular5 and what I need is for a user to be able to switch languages. I\'ve never had to implement this in an Angular2+ (actu

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 20:01

    Instead of using ng-translate you can use config file and language json files for that the you can place that json file in your server location and access it easily from angular

    in config.json u can defile language type

    { 
      "LANGUAGE": "fr.json" 
    
    }
    

    in en/fr.json file

    {
        "TITLE": "Bonjour Angular avec translate !",
        "SELECT": "Changer la langue"
    
    }
    

    hear is the sample code

    App.component

    export class AppComponent  {
    
      name =  LAN_CONFIG['TITLE'];
      // name =  APP_CONFIG['LANGUAGE'];
    }
    

    OR

    You Can Use config.js file

    add this code segment to index.html header section

    
    

    config.js file

    window.config= {};
    window.config['LANGUAGE'] = 'er.js';
    

    you can access that variable to access value using

    @Injectable()
    export class LanguageService {
    
      appConfig:AppConfigService;
      lanTypePath ='../../assets/i18n/'+ window['config'].LANGUAGE;
     constructor(private http: HttpClient)
      {
        console.log(APP_CONFIG['LANGUAGE']);
      }
    
      public load()
      {
        return new Promise((resolve, reject) => {
    
          this.http.get(this.lanTypePath).catch((error: any): any => {
    
            reject(true);
            return Observable.throw('Server error');
          }).subscribe((envResponse :any) => {
            let t = new LanConfig();
            //Modify envResponse here if needed (e.g. to ajust parameters for https,...)
            LAN_CONFIG = Object.assign(t, envResponse);
            resolve(true);
          });
    
        });
      }
    
    }
    

    think this method better than previous for your situation

    Github demo

    Hope this will helps..!

提交回复
热议问题