Ionic 2:在 ts 文件中使用 ng2-translate

Ionic 2 : Use ng2-translate in a ts file

我想在 object 中使用翻译以在 Ionic 2 上使用 toast。但我不明白如何在 .ts 文件中使用 ng2-translate... 有人可以给我举个例子吗?

我想在我的菜单中对标题进行翻译。我这样尝试但它不起作用:

constructor(public platform: Platform, public menu: MenuController, public translate : TranslateService) {
this.initializeApp();

translate.setDefaultLang('fr');
translate.use('fr');
let testTrad : string = 'Accueil';

translate.get('TEST').subscribe(res => {testTrad = res; console.log(testTrad)});
console.log(testTrad);

// Remplissage du tableau des pages.
this.pages= [
  {title: testTrad ,                  component: TabsPage},
  {title: 'Mon compte',               component: MyAccountPage},
  {title: 'Changer de mot de passe' , component: ChangePasswordPage},
  {title: 'Documents' ,               component: DocumentsPage}
]

它必须在我的菜单上显示 "test",但它继续显示 "Accueil"。

不对,

translate.get('TEST').subscribe(res => {testTrad = res; console.log(testTrad)});
console.log(testTrad);

// Remplissage du tableau des pages.
this.pages= [
  {title: testTrad ,                  component: TabsPage},
  {title: 'Mon compte',               component: MyAccountPage},
  {title: 'Changer de mot de passe' , component: ChangePasswordPage},
  {title: 'Documents' ,               component: DocumentsPage}
]

.subscribe 是异步的,因此 中分配的值 subscribe 尚不可访问

尝试

translate.get('TEST').subscribe(res => {
    testTrad = res; 
    console.log(testTrad);
    this.pages= [
       {title: testTrad ,                  component: TabsPage},
       {title: 'Mon compte',               component: MyAccountPage},
       {title: 'Changer de mot de passe' , component: ChangePasswordPage},
       {title: 'Documents' ,               component: DocumentsPage}
    ]
});
console.log(testTrad);

或者,如果您不想等待异步完成,您可以尝试

this.pages= [
  {title: 'Mon compte',               component: MyAccountPage},
  {title: 'Changer de mot de passe' , component: ChangePasswordPage},
  {title: 'Documents' ,               component: DocumentsPage}
]
translate.get('TEST').subscribe(res => {
   testTrad = res;
   this.pages.push({title: testTrad, component: TabsPage});
 });