Anyone tried the Translate service?

Hi,

I wanted to try the translate service, but could not make it work.

My file imports Translate and TranslatePipe.

I assigned the TranslatePipe to pipes.

In my constructor, I added translate.translations(‘fr’, { ‘Hi’: ‘Bonjour’});

In my template, I have {{ ‘Hi’ | translate }}.

Nothing is displayed. If I put in the constructor translate.setLanguage(‘fr’), I will see ‘Bonjour’.

Why the English version does not show up?

Thanks

Hi,

I have successfully implemented ng2-translate to Ionic2 project. Here are the steps you need to do:

  1. npm install ng2-translate --save

  2. open you app.js and import service like this:

     import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate';
    
  3. Then update @App like this:

     @App({
        templateUrl: 'build/app.html',
        config: {},
        providers: [TranslateService, HeroesService]
        pipes: [TranslatePipe]
     })
    

And constructor:

export class MyApp {
  constructor(
       platform: Platform,
       app: IonicApp,
       translate: TranslateService,
       heroes: HeroesService
  ) {
  this.platform = platform;
  this.app = app;
  this.translate = translate;
  this.translationConfig();
  this.initializeApp();
  this.root = News;
}

initializeApp() {
    this.platform.ready().then(() => {
       console.log('Platform ready');
    });
}

// TODO: implement ng2-translate when they'll fix
translationConfig() {
    var prefix = 'assets/i18n/';
    var suffix = '.json';
    this.translate.useStaticFilesLoader(prefix, suffix);
    var userLang = navigator.language.split('-')[0]; // use navigator lang if available
    userLang = /(de|en)/gi.test(userLang) ? userLang : 'en';

    // optional, default is "en"
    this.translate.setDefaultLang('en');

    // the lang to use, if the lang isn't available, it will use the current loader to get them
    this.translate.use(userLang);
  }
  1. put your en.json (for english language) in /www/assets/i18n/ (my example)

  2. use this in template:

    {{'FOO' | translate}}

  3. To use in your @Page *.js files, add this part of code to them:

    import {TranslateService, TranslatePipe} from ‘ng2-translate/ng2-translate’;
    import {Page, NavParams, NavController} from ‘ionic/ionic’;

      @Page({
         templateUrl: 'build/pages/News/News.html',
         pipes: [TranslatePipe]
      })
      export class News {
        constructor(
           params: NavParams,
           nav: NavController,
           translate: TranslateService
      ) {
    

Job’s done :wink:

7 Likes

Oh cool! I will try it right away.

By the way, in your code, can you retype the line just after the ‘var userLang’? I think it got changed by the Ionic textbox.

I’m sorry… looks like ionic textbox screwed the formatting a bit

translationConfig() {
var prefix = 'assets/i18n/';
var suffix = '.json';
this.translate.useStaticFilesLoader(prefix, suffix);

var userLang = navigator.language.split('-')[0]; // use navigator lang if available
userLang = /(de|en)/gi.test(userLang) ? userLang : 'en';

// optional, default is "en"
this.translate.setDefaultLang('en');

// the lang to use, if the lang isn't available, it will use the current loader to get them
this.translate.use(userLang);
}

an how the de and en.json will look like?

en.json

{
  "FOO": "Bar.",
  "SOMETHING_ELSE": "This is just another translation sentence"
}

de.json

{
  "FOO": "Bar.",
  "SOMETHING_ELSE": "Dies ist nur ein weiterer Übersetzungssatz"
}

Worked like a charm!

Now, the challenge is to find the right key names!

Do you have some advice for an app that has several views?

As you see, language files are JSON files which means you can work around with object (that’s why your lang file starts with { and ends with }) and sub objects

About best practice and keys in json files, I don’t know, but I’ve seen two version (we’re mainly using 1st one):

en.json
{
“NEWS”: “News”,
“NEWS_NO_DATA”: “No data for News page”,
“NEWS_FETCHING”: “Fetching news from server…”

“ABOUT”: “About”,
“ABOUT_LICENCE_AGREEMENT”: “I’m kidding”,
“ABOUT_EMAIL”: “…”
}

or option 2:

en.json
{
“NEWS”: {
"TITLE: “News”,
“NO_DATA”: “No data for News page”,
“FETCHING”: “Fetching news from server…”
},

“ABOUT”: {
"TITLE: “About”,
“LICENCE_AGREEMENT”: “I’m kidding”,
“EMAIL”: “…”
}
}

1 Like

I like your option 1.

If you want to use option 2, how the html will look like?

For option 2, your template will look like:

{{ "ABOUT.TITLE" | translate }}

or

{{ "NEWS.FETCHING" | translate }}

like you can see, I am a json master! :wink:

Thanks for you help. I learnt one new thing today!

Glad to hear that :smile:

Hi @lordgreg,

Another one for you. I have some strings that I want to translate that are in my .ts files.

What I found and work is this._translate.get(“MY_STRING”).value.

First of all, is the right way?

Second of all, Visual Studio Code gives me an error for “value” saying “Property ‘value’ does not exist on type ‘Observable’” You know how to get rid of it?

Thanks

Hi @icarus_31

Sorry for late response. The error Is a valid error, since .get returns Observable and the object doesn’t have any parameter .value. I’m currently in a talk with ng2-translate developer, if he can provide an “instant” function, like angular-translate has. There, you could then use this.translate.getInstant(‘key’) and you will get the proper string back. However, as he also explained… if your lang isn’t loaded yet at that time (because of Observable and not Promise), you will always get empty or undefined back.

Let’s see how it goes. The issue I’ve created for him is posted on next link: https://github.com/ocombe/ng2-translate/issues/20

You can also get the idea how you could currently get the translation string with .subscribe from the url above.

1 Like

Hi @lordgreg,

I have created a pipe and that one returns different strings. I want to translate those stings. Do you know how to import a pipe inside a pipe class?

If possible, always add an example. I sadly, don’t know what you’re trying to achieve.

I think he has a pipe that do something, then return a string collection, i think he wants to translate those string inside the pipe to avoid chaining pipes in the html, @icarus_31 correct me if i’m wrong.

@luchillo17 & @icarus_31:

If you can nest the pipes, as far as I know:

{{ (someString | processPipe) | translate }}

I think that’s what he wants to avoid, he wants that the processPipe translates internally using the translate pipe or something like that, basically usin a pipe inside another pipe so in the html you only need to call one single pipe.

This is something I’ve already explained above. There’s no “instant” method for ng2-translate atm. However, this topic would be more suitable to be posted on ng2-translate github and not ionic forums