国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

angular多語言配置詳解

2024-05-06 15:39:25
字體:
供稿:網(wǎng)友

angular的國際化方案,采用ngx-translate來實(shí)現(xiàn)。

安裝模塊:

npm install @ngx-translate/core --save

在根模塊中導(dǎo)入:

// other moduleimport {TranslateModule} from '@ngx-translate/core';@NgModule({  declarations: [    AppComponent,  ],  imports: [    // other module    TranslateModule.forRoot(),  ],  providers: [  ],  bootstrap: [AppComponent]})export class AppModule {}

我們希望可以在一個(gè)固定的文件里面配置對(duì)應(yīng)的翻譯文件,然后在每個(gè)用到的組件里面使用它,隨意我們需要借助TranslateHttpLoader來加載翻譯文件。首先安裝TranslateHttpLoader:

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

翻譯文件可以放在/assets/i18n/[lang].json中,[lang]代表使用的語言文件名稱。然后我們可以在跟組件中添加配置對(duì)應(yīng)的加載項(xiàng):

// other moduleimport {TranslateModule} from '@ngx-translate/core';// 自定義加載方法export function HttpLoaderFactory(http: HttpClient) {  return new TranslateHttpLoader(http, './assets/i18n/', '.json?');}@NgModule({  declarations: [    AppComponent,  ],  imports: [    // other module    TranslateModule.forRoot({      loader: {        provide: TranslateLoader,        useFactory: HttpLoaderFactory,        deps: [HttpClient],      }    }),  ],  providers: [  ],  bootstrap: [AppComponent]})export class AppModule {}

然后我們?cè)诜g文件中配置一個(gè)簡單的示例:

// /asserts/il8n/en.json{ "Hello": "hello, {{value}}", "Introduce": {  "Name": "my name is {{name}}.",  "Today": "today is {{date}}, and now time is {{time}}" }}

應(yīng)用的時(shí)候我們可以使用點(diǎn)語法,例如:Introduce.Name。

好了,定義好之后再來看如何使用。我們可以使用服務(wù)或管道或指令的方式來達(dá)到顯示語言的效果。在使用之前,我們需要在應(yīng)用中初始化TranslateService:

import { Component } from '@angular/core';import {TranslateService} from '@ngx-translate/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less']})export class AppComponent { constructor(   public translate: TranslateService, ) {   this.translate.setDefaultLang('en');   this.translate.use('en'); }}

我傾向于在跟組件的construct里面初始化TranslateService,因?yàn)橐粋€(gè)系統(tǒng)的翻譯是統(tǒng)一的,在開始應(yīng)用的時(shí)候就需要設(shè)置好默認(rèn)語言。這里使用translate.setDefaultLang('en')來設(shè)置默認(rèn)語言為英文。然后使用translate.user('en')手動(dòng)選擇使用英文。在切換語言的時(shí)候,我們使用translate.user([lang])來設(shè)置啟用哪個(gè)語言。

最后來使用翻譯,有多種使用的方式。來看看。

使用方式

使用Service的方式

在運(yùn)行的時(shí)候,會(huì)先發(fā)起個(gè)請(qǐng)求通過Http獲取翻譯文件,通過Observable的方式應(yīng)用參數(shù)上去,然后獲得翻譯的內(nèi)容。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 察隅县| 集贤县| 枣庄市| 十堰市| 纳雍县| 苏尼特左旗| 金堂县| 育儿| 永德县| 克拉玛依市| 那曲县| 雷波县| 江西省| 富裕县| 甘谷县| 阿坝县| 尤溪县| 崇州市| 且末县| 武乡县| 赞皇县| 台东县| 中方县| 天门市| 卢氏县| 萨嘎县| 朝阳县| 连云港市| 景德镇市| 新昌县| 葵青区| 昌吉市| 彝良县| 无极县| 新民市| 林芝县| 当雄县| 武平县| 牙克石市| 怀集县| 武安市|