在Angular中,我们可以使用i18n来实现国际化和本地化,而在构建应用程序时,我们需要把i18n翻译成多种语言。但是在构建过程中,我们可能会遇到一些维护问题,例如:
下面是如何更容易地维护i18n构建的步骤:
步骤1:使用Excel或Google Sheet等工具来管理所有翻译。在第一列中添加翻译的key值,在其余列中添加不同语言的翻译。
例如:
key | en | zh |
---|---|---|
hello | Hello | 你好 |
world | World | 世界 |
步骤2:在Angular中使用ngx-translate库。它提供了多种选项来加载和使用所有翻译。
安装:
npm install @ngx-translate/core --save
步骤3:为每个语言和翻译文件创建一个JSON文件。例如:
en.json
{
"hello": "Hello",
"world": "World"
}
zh.json
{
"hello": "你好",
"world": "世界"
}
步骤4:创建一个Service来加载和使用所有翻译。在服务中,我们可以使用use()
方法加载选择的语言和翻译文件,并使用get()
方法获取特定翻译的value。
例如:
app-translate.service.ts
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Injectable({ providedIn: 'root' })
export class AppTranslateService