参考文献 : 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个方法呼叫。
- 使用APP_INITIALIZER ,并创建一个工厂方法来进行初始化
- 在app.component.ts中呼叫,例如
constructor(private translationService: TranslationService) { }
export class AppComponent implements OnInit{
ngOnInit(): void {
this.translationService.init('en');
}
}
使用方法
- 使用管道
<mat-label>{{'login.username' | translate}}</mat-label>
<input type="text" placeholder="{{'login.username' | translate}}" />
- 使用translate属性
<mat-error
translate="login.validationMessages.passwordRequired">
</mat-error>
- 使用指令
<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; );
}
}