2016-07-31 41 views
0

我只查看ng2Translate,因此我可以在我的Ionic2/Angular2項目中使用它進行本地化。我已經設置和工作,並根據文檔使用時得到正確的標記值...如何從Angular2中獲取字符串值ng2Translate TranslateService方法

<div>{{myVal}}</div> 
<div>{{ 'COMMON.HELLO' | translate:{value: "world"} }}</div> 

和我的字符串值通過罰款。

我現在想嘗試在後面的代碼中獲取一些字符串,並將它們分配給組件變量,然後我可以將它們綁定到標記中,如下所示。

@Component({ 
templateUrl: 'build/pages/sidemenu-page/sidemenu-page.html', 
pipes: [TranslatePipe] 
}) 
export class SideMenuPage { 
    public rootPage = SideMenuPage; 

    public myVal: string; 

    constructor(private menu: MenuController, private nav: NavController, private tranlate: TranslateService){ 
    let temp = tranlate.get("MYTESTVAL"); 
    this.myVal = temp.first(); // <-- type error first does not return a string 
    } 

,然後用它...

<div>{{myVal}}</div> 

tranlate.get返回觀察到的RxJs(這我剛開始看,我以前沒有使用過) - 我只是不明白如何從中獲取「原始字符串值」。事件first似乎仍然返回可觀察。

任何人都可以讓我知道如何獲得字符串?

+0

嘗試'this.myVal =溫度;'和'{{myVar的|異步}}' – yurzui

回答

0

閱讀的RxJs,它看起來像所有我需要做的是

temp.subscribe(x => this.myVal = x) 

這肯定似乎在任何速率工作。

[更新] 事件更好,有一個瞬間的方法.. this.myVal = tranlate.instant("MYTESTVAL");

0

您是否嘗試過這樣的:

@Component({ 
    templateUrl: 'build/pages/sidemenu-page/sidemenu-page.html', 
    pipes: [TranslatePipe] 
}) 
export class SideMenuPage { 
    public rootPage = SideMenuPage; 

    public myVal: string; 
    public sub: any; 

    constructor(private menu: MenuController, private nav: NavController, private tranlate: TranslateService){ 
    this.sub = tranlate.get("MYTESTVAL").subscribe(value=>this.myVal=value,error=>console.log(error)); 
    } 

    ngOnDestroy(){ 
    this.sub.unsubscribe(); 
} 
}