我只是在查看 ng2Translate,这样我就可以在我的
Ionic2 / Angular2
项目中使用它进行本地化。我已设置并运行它,并在根据文档使用时在标记中获取正确的值...
<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 observable(我刚刚开始看,我之前没有使用过它们) - 我只是不知道如何从中获取“原始字符串值”。事件 first
似乎仍然返回一个可观察的值。
谁能告诉我如何获得字符串?
你试过这个吗:
@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();
}
}
阅读 RxJs,看起来我只需要做这件事
temp.subscribe(x => this.myVal = x)
无论如何,这似乎确实有效。
更好的是,有一个即时方法:
this.myVal = tranlate.instant("MYTESTVAL");