一、ngx-translate认识
ngx-translate:The internationalization (i18n) library for Angular.
二、安装
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
三、项目中配置使用ngx-translate
将TranslateModule
引入到应用的根模块ngModule
中
import {
BrowserModule} from '@angular/platform-browser';
import {
NgModule} from '@angular/core';
import {
TranslateModule} from '@ngx-translate/core';
import {
HttpModule, Http } from '@angular/http'; //注意:这是angular版本低于4.3引入方法,以后都以此替代,import {HttpClientModule, HttpClient} from '@angular/common/http';
// AoT requires an exported function for factories
export function HttpLoaderFactory(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
defaultLanguage: 'en',
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [Http]
}
})
],
bootstrap: [AppComponent]
})
export class AppModule {
}
在app.component.ts
中引入TranslateService
import {
Component} from '@angular/core'