2017-03-22 38 views
0

嗨,我很難翻譯ts文件中的文本,例如使用ng-2翻譯的警報和彈出窗口。我已經做了翻譯HTML,那是很簡單,但我現在卡住了,比方說,例如,我的代碼是這樣的:需要幫助翻譯我的ts文件中的文本

showAlert() { 
let alert = this.alertCtrl.create({ 
title: 'Confirmed', 
subTitle: this.ride.type == "rider" ? 'Your ride request has been created.' : 'Your ride offer has been created.', 
buttons: [{ 
text: 'Ok', 
handler:() => { 
alert.dismiss() 
.then(()=>{ 
this.navCtrl.pop(); 
}) 
return false; 
} 
}] 
}); 
alert.present(); 
} 

} 

如何翻譯的標題和副標題?我已經在json文件中有鍵和相應的翻譯文本,但我不知道如何在這裏進行句法分析。在html文件中,它只是{{KEY |翻譯}}但不知道它會在這裏。任何幫助將不勝感激,謝謝!

回答

2

您需要使用TranslateService。 你有兩種方法:即時和獲得。 個人我總是使用即時,因爲我100%確定我的翻譯文件已加載。 我用get寫了一個例子,但它可能是錯誤的(未測試)。

import { TranslateService } from "ng2-translate"; 

constructor(
     protected translateService: TranslateService 
) { 
} 

/* instant(key: string|Array<string>, interpolateParams?: Object): string|Object: Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead. */ 
showAlert() { 
    let alert = this.alertCtrl.create({ 
     title: this.translateService.instant('KEY'), 
     subTitle: this.ride.type == "rider" ? this.translateService.instant('KEY2') : this.translateService.instant('KEY3') 
    }); 
} 

/* otherwise */ 
showAlert() { 
    this.translateService.get('KEY') 
    .flatMap((trad) => { 
     let key; 
     if (this.ride.type == "rider") { 
      key = 'KEY2'; 
     } else { 
      key = 'KEY3'; 
     } 
     return this.translateService.get(key).map((trad2) => { 
        return { trad: trad, trad2: trad2 }; 
       }); 
    }) 
    .subscribe((trads: { trad: string, trad2: string }) => { 
     let alert = this.alertCtrl.create({ 
      title: this.translateService.instant(trads.trad), 
      subTitle: trads.trad2 
     }); 
    }, 
    (error) => { 
     // ERROR HERE (SUBSCRIBE NOT CALLED) 
    }); 
} 
+0

工程就像一個魅力。謝謝一堆! :) – BleachedAxe

0

您可以在您的控制器中注入TranslateService,然後使用獲取方法獲取翻譯後的字符串。

get(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object> 

您可以在組件中看到獲取值的方法。請記住,它會直接返回可觀察值而非翻譯的值。