Begum
Begum

Reputation: 91

How to use TranslateHttpLoader with service url in ngx-translate

I am trying to get translated text from content management system with service URL. When I use a JSON file it works well, but how can I use a service URL to get translated data?

This is the code that's not working:

export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, 'http://test.test.com/test/test/Translations/{lang}/{SiteId}');
}    

Upvotes: 8

Views: 21619

Answers (3)

Ravi
Ravi

Reputation: 1

Your approach is absolutely correct. But that creates another problem. We cannot keep the language fetch URL static in HttpLoaderFactory. It may be dynamic some time. And the solution provided by Viswa is for dynamic URL. Using service we can provide the dynamic URL to fetch the translated language from the database.

Upvotes: 0

Bharat Raj Saya
Bharat Raj Saya

Reputation: 39

I ran into the same issue when trying to move from 'assets/i18n/english.json' etc to MySQL database for fetching the translated values dynamically from a table. I wanted to do this so that the admin can change them on his own.

So, I tried the answer given by Viswa and it works but I found a simpler way of doing this HttpLoaderFactory. Just add the following to your app.module.ts. Replace the URL with your API. Mine was like 'http://localhost:8080/translation/:language'

export function HttpLoaderFactory(http: HttpClient) {  
  return new TranslateHttpLoader(http, "http://localhost:8080/translation/", "");
}

Another thing that wasted some time as I was sending an array of objects like [{name: 'Name'}] instead of sending just an object like {name: 'Name'}. Once that was fixed, it worked like a charm!

Upvotes: 1

Viswa
Viswa

Reputation: 821

Yesterday I have faced the same issue on how to make use of JSON response from API calls using ngx-translate and I have identified the solution. I know its very late to update here, but I believe some one will get benefit out of it.

Ngx-translate offers to use Service if you are not going to use .json file. For this, in your *.module.ts file, "useClass" instead of "useFactory" like below.

 @NgModule({
      imports: [SharedModule, SharedComponentsModule, routing,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: TranslationService,
            //useFactory : HttpLoaderFactory,
            deps: [HttpClient]
          }

In your Translation Service, just make call of API url something like this.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { TranslateLoader } from '@ngx-translate/core';

@Injectable()
export class TranslationService implements TranslateLoader {

    constructor(private http: HttpClient) { }

    getTranslation(lang: string): Observable<any> {
    return this.http.get(`http://<someurlreferences>?language=${lang}`)
    .map((response: JSON) => {
    return response;
    });
    }   
}

Remember: The API response should be in JSON format. Else, ngx-translate would not translate.

Assuming your JSON response is in below Format

{
    "Data": {
        "First": [{
            "key": "FirstKey",
            "value": "FirstValue"
        }]
    }
}

Then, in your *.component.ts file

import { Component, OnInit } from '@angular/core'
import { TranslateService } from '@ngx-translate/core';

@Component({
  template: `<button (click)="switchLanguage('en')" >English</button>
            <button (click)="switchLanguage('cy')" >Welsh</button>
             <h1>{{'Data.First.0.value' | translate }} <!--FirstValue--> 
                    </h1>`

export class SomeComponent implements OnInit {
constructor(private translate: TranslateService) {
      translate.addLangs(['en', 'cy']);
      translate.setDefaultLang('en');

      const browserLang = translate.getBrowserLang();
      translate.use(browserLang.match(/en|cy/) ? browserLang : 'en');
     }
    switchLanguage(language: string) {
    this.translate.use(language);
  }
}

The UI displays two buttons (English and Welsh) and on clicking, the service API url will be called based on language parameter accordingly.

Upvotes: 23

Related Questions