我正在按照这个教程在Angular2中实现翻译-它运行良好,但是我希望只在点击相应的语言按钮时加载json文件。有人可以帮忙吗?
// app/translate/translation.ts
import { OpaqueToken } from '@angular/core';
// import translations(I dont want to import all languages here)
import { LANG_EN_NAME, LANG_EN_TRANS } from './lang-en';
import { LANG_ES_NAME, LANG_ES_TRANS } from './lang-es';
import { LANG_ZH_NAME, LANG_ZH_TRANS } from './lang-zh';
// translation token
export const TRANSLATIONS = new OpaqueToken('translations');
// all translations
const dictionary = {
[LANG_EN_NAME]: LANG_EN_TRANS,
[LANG_ES_NAME]: LANG_ES_TRANS,
[LANG_ZH_NAME]: LANG_ZH_TRANS,
};
// providers
export const TRANSLATION_PROVIDERS = [
{ provide: TRANSLATIONS, useValue: dictionary },
];
// app/translate/translate.service.ts
import {Injectable, Inject} from '@angular/core';
import { TRANSLATIONS } from './translations'; // import our opaque token
@Injectable()
export class TranslateService {
private _currentLang: string;
public get currentLang() {
return this._currentLang;
}
// inject our translations
constructor(@Inject(TRANSLATIONS) private _translations: any) {
}
public use(lang: string): void {
// set current language
this._currentLang = lang;
}
private translate(key: string): string {
// private perform translation
let translation = key;
if (this._translations[this.currentLang] && this._translations[this.currentLang][key]) {
return this._translations[this.currentLang][key];
}
return translation;
}
public instant(key: string) {
// call translation
return this.translate(key);
}
}
import {NgModule} from '@angular/core';
import {TRANSLATION_PROVIDERS} from './translations';
import {TranslatePipe} from './translate.pipe';
import { TranslateComponent} from './translate.component';
import { CommonModule } from '@angular/common';
@NgModule({
imports: [
CommonModule
// PaginatorModule
],
declarations: [TranslatePipe,TranslateComponent],
providers: [
TRANSLATION_PROVIDERS
],
exports: [TranslateComponent,TranslatePipe]
})
export class TranslationModule {}
更新 - 我按照这个tutorial添加了ngx-translate到我的项目中。但是我无法让它在懒加载的子模块中工作。有人可以帮我吗?
//我的代码在应用程序模块中运行良好,但在这里不起作用。
import { NgModule } from '@angular/core';
import { LoginComponent } from './login.component';
import { LoginRoutes } from './login.routing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http : HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
imports: [LoginRoutes,ReactiveFormsModule, CommonModule,
HttpClientModule,
TranslateModule.forChild({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
isolate: true
})],
declarations: [
LoginComponent
]
})
export class LoginModule {
constructor() {
}
}
TranslateModule.forRoot()
。 - user3411864