0

我想在对象中使用翻译来使用 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}
]

它必须在我的菜单上显示“测试”,但它继续显示“Accueil”。

4

1 回答 1

2

不,那是正确的,

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});
 });
于 2016-11-30T10:08:14.483 回答