2017-03-22 37 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> 

您可以在组件中看到获取值的方法。请记住,它会直接返回可观察值而非翻译的值。