How to use TranslateHttpLoader with service url in ngx-translate

Begum picture Begum · Jun 21, 2017 · Viewed 8.9k times · Source

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}');
}    

Answer

Viswa picture Viswa · Jun 13, 2018

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.