angular国际化配置很简单,但是想不用json文件用yaml文件,并且同一语言分label.jp.yaml和message.jp.yaml两个文件分开管理。
1、下载ngx-translate的依赖库
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
2、app.module.ts 中引入TranslateModule模块
import {HttpClient, HttpClientModule} from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
imports: [
......
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpYamlLoaderFactory,
deps: [HttpClient]
}
})
],
export function HttpYamlLoaderFactory(http: HttpClient): MultiTranslateLoader {
const localPath = 'assets/i18n/';
const resources = [
{ prefix: `${localPath}label.`, suffix: '.yaml' },
{ prefix: `${localPath}message.`, suffix: '.yaml' }
];
return new MultiTranslateLoader(http, resources);
}
3、自建 MultiTranslateLoader 文件
import * as merge from 'deepmerge';
import * as jsyaml from 'js-yaml';
import { forkJoin, Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { TranslateLoader } from '@ngx-translate/core';
export interface ITranslationResource {
prefix: string;
suffix: string;
}
export class MultiTranslateLoader implements TranslateLoader {
constructor(
private http: HttpClient,
private resources: ITranslationResource[]
) { }
public getTranslation(lang: string): Observable<any> {
const requests = this.resources.map(resource => {
const isYaml = resource.suffix.includes('yaml');
const path = resource.prefix + lang + resource.suffix;
return this.http
.get(path, {
responseType: 'text'
})
.pipe(
catchError(() => {
console.error('Could not find translation file:', path);
return of({});
}),
map(res => {
if (!res) {
return {};
}
if (isYaml) {
return jsyaml.safeLoad(res.toString());
} else {
return JSON.parse(res.toString());
}
})
);
});
return forkJoin(requests).pipe(map(response => merge.all(response)));
}
}
4、创建国际化文件
label.ja.yaml
Button:
Yes: はい
No: いいえ
message.ja.yaml
Mes01: 入力が不正です。
5、注入TranslateService 服务
在需要用到的component里面注入TranslateService
import {TranslateService} from '@ngx-translate/core';
constructor(private translate: TranslateService) {
this.translate.use('ja');
}
6、使用国际化
<span>{{'Mes01' | translate}}</span><br/>
<button>{{'Button.Yes' | translate}}</button>
<button>{{'Button.No' | translate}}</button>
标签:http,自定义,return,yaml,import,translate,ngx From: https://blog.51cto.com/u_12374018/6195459