Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular6 - load translations using API call to backend using ngx-translate

I want to use ngx-translate in my frontend to dynamically load translations on app load.

My backend returns a response in JSON format, ex:

{
   "something: "something"
}

I want to use that output on my TranslateLoader instead of a local en.json file.

Is there any way to achieve that?

TL;DL: I want to call 'http://localhost:xxxx/api/translation/EN' to get a JSON response of the translations and load it on TranslateHttpLoader

like image 989
jdoe1010 Avatar asked Sep 04 '18 11:09

jdoe1010


2 Answers

You can create a factory:

export function httpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, "http://localhost:xxxx/api/translation/", "");
}

And use it in your @NgModule imports:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: httpLoaderFactory,
    deps: [HttpClient]
  }
}),
like image 116
Oram Avatar answered Oct 06 '22 13:10

Oram


We can achieve using TranslateLoader provider with Custom Loader Class

In Module :

export class CustomLoader implements TranslateLoader {

  constructor(private http: Http) {}

  public getTranslation(lang: String): Observable<any> {
    return this.http.get(URL).map(
      (res: any) => {
        return res;
      }
    );

  }
}

@NgModule({
  imports: [
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useClass: CustomLoader,
      // useFactory: (createTranslateLoader),
      deps: [Http]
    })
  ]
}) 

In Component:

 constructor(private _translate: TranslateService){}

 const transText = this._translate.instant('something');
like image 4
Suresh Kumar Ariya Avatar answered Oct 06 '22 15:10

Suresh Kumar Ariya