简体   繁体   中英

How to get a string value from Angular2 ng2Translate TranslateService method

I am just looking at ng2Translate so I can use it for localization in my Ionic2 / Angular2 project. I have it set up and working, and get the correct values in markup when using according to the documentation...

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

and my string values come through fine.

I now wanted to try and get some strings in code behind, and assign these to component variables, which I can then bind to in the markup, as in the following.

@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
  }

and then use it...

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

The tranlate.get returns an RxJs observable (which I am just starting to look at, I have not used them before) - and I just cannot see how to get the "raw string value" from it. Event the first still seems to return an observable.

Can anyone let me know how to get the string?

Reading on the RxJs, it looks like all I need to do it

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

this certainly seem to work at any rate.

[UPDATE] Event better, there is an instant method.. this.myVal = tranlate.instant("MYTESTVAL");

Have you tried this:

@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();
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM