typescript 用于多语言支持的 Angular 6 CLI 本地化和国际化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51111329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 6 CLI localisation & Internationalization for multilingual support
提问by Dinesh Ghule
We are using Angular 6 in our Application. In that application we want to give multilingual support.
我们在我们的应用程序中使用 Angular 6。在该应用程序中,我们希望提供多语言支持。
How can we implement localisation & Internationalization in angular 6? Its an angular 6 version.
我们如何在 Angular 6 中实现本地化和国际化?它是一个 angular 6 版本。
回答by Dinesh Ghule
Refer: https://dgwebidea.blogspot.com/2020/01/angular-internationalization-and.html
参考:https: //dgwebidea.blogspot.com/2020/01/angular-internationalization-and.html
Translate Angular 6 apps with ngx-translate What we will do:
使用 ngx-translate 翻译 Angular 6 应用程序我们将做什么:
Create minimal Angular6 project Install and load ngx-translate Init the TranslateService Create .json translation files Translate simple title and intro Integrate language switcher Translate sentence with variable
创建最小的 Angular6 项目 安装并加载 ngx-translate 初始化 TranslateService 创建 .json 翻译文件 翻译简单的标题和介绍 集成语言切换器 翻译带有变量的句子
Using nested .json objects
使用嵌套的 .json 对象
Create minimal Angular6 project
创建最小的 Angular6 项目
We use @angular/cli to create a new project named “traduction” in the terminal:
我们使用@angular/cli 在终端中创建一个名为“traduction”的新项目:
ng new traduction --prefix tr
cd traduction
ng serve -o
Install and load ngx-translate
安装和加载 ngx-translate
Use npm in your terminal within the project folder “traduction”:
在项目文件夹“traduction”中的终端中使用 npm:
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader
Note: Use following versions forbelow angular 6
注意:使用以下版本 forbelow angular 6
"@ngx-translate/core": "^9.1.1"
"@ngx-translate/http-loader": "^3.0.1"
and for angular 5 use latest version 10 and above
对于 angular 5,请使用最新版本 10 及更高版本
Import the necessary modules into app.module.ts :
将必要的模块导入 app.module.ts :
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
Add a function, that returns a “TranslateHttpLoader” and export it (needed by AoT). In this case the HttpLoaderFactory function we create, returns a Object that can load Translations using Http and .json, but you could write your own Class that for example uses a global JavaScript variable instead of loading a file, or that uses Google Translate:
添加一个函数,该函数返回“TranslateHttpLoader”并将其导出(AoT 需要)。在这种情况下,我们创建的 HttpLoaderFactory 函数返回一个可以使用 Http 和 .json 加载翻译的对象,但您可以编写自己的类,例如使用全局 JavaScript 变量而不是加载文件,或者使用谷歌翻译:
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
OR
或者
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}
We then need to import our modules into the @NgModule, this is the import that tells Angular to load this Module into your AppModule:
然后我们需要将我们的模块导入@NgModule,这是告诉 Angular 将此模块加载到您的 AppModule 的导入:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
Inject the TranslateService
注入翻译服务
In “app.component.ts” we now init the “TranslateService”, we import the TranslateService:
在“app.component.ts”中,我们现在初始化“TranslateService”,我们导入TranslateService:
import { TranslateService } from '@ngx-translate/core';
Then inside the AppComponent Class we inject the service and define our default language. And to be ready for the next step, we add a function to switch the language.
然后在 AppComponent 类中我们注入服务并定义我们的默认语言。为了为下一步做好准备,我们添加了一个功能来切换语言。
constructor(private translate: TranslateService) {
translate.setDefaultLang('en');
}
switchLanguage(language: string) {
this.translate.use(language);
}
Create .json translation files
创建 .json 翻译文件
We now create our translation files inside the assets/i18n folder:
我们现在在 assets/i18n 文件夹中创建我们的翻译文件:
src/assets/i18n/en.json
{
"Title": "Translation example",
"Intro": "Hello I am Arthur, I am 42 years old."
}
src/assets/i18n/fr.json
{
"Title": "Exemple de traduction",
"Intro": "Bonjour je m'appelle Arthur, j'ai 42 ans."
}
These are simple .json files that will be loaded by our “TranslateHttpLoader” we created in “app.module.ts”.
这些是简单的 .json 文件,将由我们在“app.module.ts”中创建的“TranslateHttpLoader”加载。
Translate simple title and intro
翻译简单的标题和介绍
In app.component.html we add a header with the translate “directive” inside the “h1” tag. This directive will take the text inside the tag and replace it with the matching translation. If you use the directive you have to make sure, that there is nothing else inside the tag but the text.
在 app.component.html 中,我们在“h1”标签内添加了一个带有翻译“指令”的标题。该指令将获取标签内的文本并将其替换为匹配的翻译。如果您使用该指令,您必须确保标签内除了文本之外没有其他内容。
As a second example we use the “TranslationPipe” to translate a label with define as a inline string. As we sometimes have value inside a translation that we want to replace, we can pass a data object into the “translate” pipe.
作为第二个示例,我们使用“TranslationPipe”来翻译带有定义为内联字符串的标签。由于有时我们想要替换的翻译中有值,我们可以将数据对象传递到“翻译”管道中。
<h1 translate>Title</h1>
<div>
{{ 'Intro' | translate:user }}
</div>
Integrate language switcher
集成语言切换器
We can now attach our language switcher function that we saw above in app.component.ts to a button. In this case we create a button for each language and call the switchLanguage() function with the matching language key.
我们现在可以将我们在 app.component.ts 中看到的语言切换器功能附加到按钮上。在这种情况下,我们为每种语言创建一个按钮,并使用匹配的语言键调用 switchLanguage() 函数。
<button (click)="switchLanguage('en')">en</button>
<button (click)="switchLanguage('fr')">fr</button>
Translate sentence with variable
用变量翻译句子
As mentioned before, you sometimes have sentences to that contain variable. In this little example we have a user object with age and name inside the “app.component.ts”, and we want to translate a sentence that will contain this values:
如前所述,您有时会遇到包含变量的句子。在这个小例子中,我们在“app.component.ts”中有一个带有年龄和名称的用户对象,我们想要翻译一个包含以下值的句子:
...
export class AppComponent {
user = {
name: 'Arthur',
age: 42
};
...
}
Because we pass this object into the “translate” pipe, we can now use it's properties in our translation with the {{ placeholder }} notation.
因为我们将此对象传递到“翻译”管道中,所以我们现在可以在翻译中使用 {{ placeholder }} 符号使用它的属性。
src/assets/i18n/en.json
{
"Title": "Translation example",
"Intro": "Hello I am {{name}}, I am {{age}} years old."
}
src/assets/i18n/fr.json
{
"Title": "Exemple de traduction",
"Intro": "Bonjour je m'appelle {{name}}, j'ai {{age}} ans."
}
Using nested .json objects
使用嵌套的 .json 对象
If you want to be able to have more control on your translation, and for example translate page blocks (from the end-user perspective) or components (from the developer perspective), one solution could be the following; use nested .json objects as described in the git repo. An example could look like this in the -json files:
如果您希望能够更好地控制您的翻译,例如翻译页面块(从最终用户的角度)或组件(从开发人员的角度),一种解决方案可能如下:使用 git repo 中描述的嵌套 .json 对象。-json 文件中的示例可能如下所示:
{
"Title": "Translation example",
"Intro": "Hello I am {{name}}, I am {{age}} years old.",
"Startpage": {
"TranslationSections": "Hello World"
},
"Aboutpage": {
"TranslationSections": "We are letsboot"
}
}
{
"Title": "Exemple de traduction",
"Intro": "Bonjour je m'appelle {{name}}, j'ai {{age}} ans.",
"Startpage": {
"TranslationSections": "Bonjour Monde"
},
"Aboutpage": {
"TranslationSections": "Nous sommes letsboot"
}
}
And in the corresponding template:
并在相应的模板中:
<h1 translate>Title</h1>
<div>
{{ 'Intro' | translate:user }}
</div>
<div>
{{ 'Startpage.TranslationSections' | translate }}
</div>
<div>
{{ 'Aboutpage.TranslationSections' | translate }}
</div>
<br/>
<button (click)="switchLanguage('en')">en</button>
<button (click)="switchLanguage('fr')">fr</button>
回答by Tienanhvn
component.module.ts
组件.module.ts
export function translateHttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: translateHttpLoaderFactory,
deps: [HttpClient]
}
})
class LanguagService.ts
类语言服务.ts
import { Injectable } from '@angular/core';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
import { ReplaySubject } from 'rxjs';
import { take } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class LanguageService {
language$ = new ReplaySubject<LangChangeEvent>(1);
translate = this.translateService;
// 國旗對照;
constructor(private translateService: TranslateService) {}
setInitState() {
this.translateService.addLangs(['en', 'cn','vi']);
console.log( 'Browser Lang', this.translate.getBrowserLang());
const browserLang = (this.translate.getBrowserLang().includes('vi')) ? 'vi' : 'cn' ;
console.log("anhtt "," anguage = " +browserLang);
this.setLang(browserLang);
}
setLang(lang: string) {
this.translateService.onLangChange.pipe(take(1)).subscribe(result => {
this.language$.next(result);
});
this.translateService.use(lang);
}
}
app.component.html
应用程序组件.html
<h1>How to multi language in angular 7</h1>
<p >{{'content' |translate}}</p>
<h4 translate>
{{'message' |translate}}
</h4>
<button (click)="selectLanguageEN()">English</button>
<button (click)="selectLanguageCN()">中國</button>
<button (click)="selectLanguageVI()">Viet Nam</button>
Code demo:
代码演示:
https://tienanhvn.blogspot.com/2019/06/angular-7-how-to-multi-language.html
https://tienanhvn.blogspot.com/2019/06/angular-7-how-to-multi-language.html