安装ngx-translatevs构建自己的翻译模块
创始人
2024-08-30 01:30:08
0次

ngx-translate是一个流行的Angular库,用于实现多语言应用程序。它提供了一个翻译服务和一个翻译指令,并使用@ngx-translate/core和@ngx-translate/http-loader依赖项。安装ngx-translate相对简单,只需在项目中运行以下命令:

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

然后需要在app.module.ts中配置翻译器:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
 
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
 
 
export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
}
 
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        })
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

然后在组件中使用翻译器指令:

{{ 'HOME.TITLE' | translate }}

如果你想构建自己的翻译模块,你需要定义一个函数,该函数将收到一个键并返回其对应的翻译字符串。例如:

import { Injectable } from '@angular/core';
 
@Injectable({
    providedIn: 'root'
})
export class TranslationService {
 
    translations = {
        'HOME.TITLE': 'Welcome Home!'
    };
 
    translate(key: string) {
        return this.translations[key];
    }
}

然后在组件中使用该服务:

import { Component } from '@angular/core';
import { TranslationService } from './translation.service';
 
@Component({
    selector: 'app

相关内容

热门资讯

正版透视器玲珑透视器多功能AI... 正版透视器玲珑透视器多功能AI教程,玲珑总是真的有透视器教程1、实时玲珑透视辅助更新:用户可以随时随...
正版开挂天天摸麻将开挂多功能A... 正版开挂天天摸麻将开挂多功能AI工具,天天摸麻将果然是有开挂工具在进入天天摸麻将软件靠谱后,参与本局...
正版外挂星聚汇外挂多功能AI脚... 正版外挂星聚汇外挂多功能AI脚本,星聚汇确实有外挂脚本1、完成星聚汇有辅助插件,帮助玩家取得所有比赛...
正版开挂盛世开挂多功能AI软件... 正版开挂盛世开挂多功能AI软件,盛世一直真的有开挂软件盛世辅助器是一种具有地方特色的麻将游戏,要想赢...
正版外挂团团竞技外挂多功能AI... 正版外挂团团竞技外挂多功能AI工具,团团竞技确实是真的有外挂工具1、许多玩家不知道团团竞技辅助怎么退...
正版外挂趣玩娱乐外挂多功能AI... 正版外挂趣玩娱乐外挂多功能AI攻略,趣玩娱乐好像真的是有外挂攻略1、每一步都需要思考,不同水平的挑战...
正版辅助哥哥打大A辅助多功能A... 您好,哥哥打大A这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这...
正版外挂胡乐安庆麻将外挂多功能... 正版外挂胡乐安庆麻将外挂多功能AI攻略,胡乐安庆麻将一贯真的有外挂攻略1、金币登录送、破产送、升级送...
正版开挂川渝互娱开挂多功能AI... 正版开挂川渝互娱开挂多功能AI攻略,川渝互娱竟然是有开挂攻略1、进入到川渝互娱是否有挂之后,能看到左...
正版辅助器兴动互娱辅助器多功能... 正版辅助器兴动互娱辅助器多功能AI插件,兴动互娱竟然存在有辅助器插件1、在兴动互娱插件功能辅助器技巧...