• Angular 多语言


    参考文献 : https://zhuanlan.zhihu.com/p/346329015

     

    安装

    npm install @ngx-translate/core --save
    npm install @ngx-translate/http-loader --save

    创建服务

    import { Injectable } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    @Injectable({  providedIn: 'root'})
    export class TranslationService {
      constructor(private translateService: TranslateService) {}
      init(locale = 'en') {
        this.translateService.addLangs(['en', 'de']);
        this.translateService.use(locale);
      }
    }

    可以使用event emitters 来监听对应的变化

    onLangChange.subscribe(
      (langChangeEvent: LangChangeEvent) => {
        // TODO: Add language change event logic
    });
    onTranslationChange.subscribe(
      (translationChangeEvent: TranslationChangeEvent) => {
        // TODO: Add translation change event logic
    });
    onDefaultLangChange.subscribe(
      (defaultLangChangeEvent: DefaultLangChangeEvent) => {
        // TODO: Add default language change event logic
    });

    编写翻译文件

    翻译文件放在src/assets/i18n目录,为json格式的文件。

    {
       "login": {
           "username": "Username",
           "password": "Password",
           "loginButton": "Login",
           "forgotPassword": "Forgot your password?",
           "validationMessage": {
             "usernameRequired": "Username is required",
             "passwordRequired": "Password is required"
           }
       },
       "home": {
           "greeting: "Hello <strong>{{username}}</strong>"
       },
       "alert": {
           "popupText": "You will be logged out in {{time}} seconds."
       }
    }

    将ngx-translate引入我们的AppModule中

    // Add necessary imports
    import {APP_INITIALIZER} from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
    import {TranslateHttpLoader} from '@ngx-translate/http-loader';
    import {TranslationService} from './shared/services/translation.service';
    export function translationInitializer(translationService: TranslationService) {
      return function () {
        return translationService.init('en');  
      };
    }
    export function createTranslateLoader(http: HttpClient) {
      return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
    }
    @NgModule({  
        imports: [
           TranslateModule.forRoot({
              defaultLanguage: 'en',
              loader: { 
                  provide: TranslateLoader,
                  useFactory: (createTranslateLoader),
                  deps: [HttpClient]
               }    
           })  
        ],  
        providers: [    
         {
            provide: APP_INITIALIZER, 
            useFactory: translationInitializer, 
            deps: [TranslationService], 
            multi: true
         }
        ]
    })
    export class AppModule {}

    TranslationService 的初始化可以被2个方法呼叫。

    1. 使用APP_INITIALIZER ,并创建一个工厂方法来进行初始化
    2. 在app.component.ts中呼叫,例如
    constructor(private translationService: TranslationService) { }
    export class AppComponent implements OnInit{
        ngOnInit(): void {
          this.translationService.init('en');
        }
    }

    使用方法

    1. 使用管道
    <mat-label>{{'login.username' | translate}}</mat-label>
    <input type="text" placeholder="{{'login.username' | translate}}" />
    1. 使用translate属性
    <mat-error 
       translate="login.validationMessages.passwordRequired">
    </mat-error>
    1. 使用指令
    <div
      [translate]="'HELLO '" 
      [translateParams]="{username: 'user123'}">
    </div

    4.服务的方式

    import {TranslateService} from '@ngx-translate/core';
    constructor(private translateService: TranslateService) { }
    export component LoginComponent {
      errorMsg: string;
      login() {
         const messageKey = 'usernameRequired';
         this.translateService.get(`login.validationMsg.${messageKey}`)
          .subscribe( message => this.errorMsg = message; );
      }
    }
  • 相关阅读:
    Spring Boot (十四): Spring Boot 整合 Shiro-登录认证和权限管理
    Spring Boot (十三): Spring Boot 小技巧
    救人一命是怎样的体验?
    如何做一个对账系统
    人工智能发展史-从图灵测试到大数据
    编程科普书籍推荐
    springcloud(十):服务网关zuul
    springcloud(九):配置中心和消息总线(配置中心终结版)
    springcloud(八):配置中心服务化和高可用
    springcloud(七):配置中心svn示例和refresh
  • 原文地址:https://www.cnblogs.com/itstac/p/14865366.html
Copyright © 2020-2023  润新知