当转换一个字符串的时候,它可以在en.json
中调用一个键,如下所示:{{ 'key' | translate }}
,但不适用于如下嵌套键:{{ 'key1.key2' | translate }}
到目前为止,我所做的是创建一个shared.module.ts
,并使用以下代码将其导入到各个所需的页面中:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
// import ngx-translate and the http loader
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';
// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
return new TranslateHttpLoader(http, '../../assets/i18n/', '.json');
}
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule,
// ngx-translate and the loader module
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
exports: [
TranslateModule
]
})
export class SharedModule { }
这个在app.component.ts
中
import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
public languages: string[] = ['en', 'ar'];
public language: string = this.languages[0];
public appPages = [];
constructor(
public platform: Platform,
private translate: TranslateService
) {
this.platform.ready().then(() => {
this.translate.addLangs(this.languages);
this.translate.setDefaultLang(this.language);
this.translate.use(this.language);
});
}
}
这是我的en.json
文件:
{
"app_title": "app title",
"app_subtitle": "app subtitle",
"login": {
"title": "login",
"subtitle": "login"
}
}
因此,如前所述,{{ 'app_title' | translate }}
工作完美,但{{ 'login.title' | translate }}
不会在结果将打印关键字'login.title',而不是实际的翻译
PS版本包括:
"@ngx-translate/core": "^14.0.0",
"@ngx-translate/http-loader": "^7.0.0",
1条答案
按热度按时间wfveoks01#
修复方法是将代码
in shared.module.ts
移动到app.module.ts
。要移动的代码为:
我们应该将TranslateModule添加到所有页面的导入中,如下所示: