ngx-translate with values in database?

Viewed 4141

I'm making an angular2 app using ngx-translate module

the service use .json documents to find the translations

first... i noticed that the local json documents route are "/src/assets/i18n/" like the next image:

enter image description here

so, the translate service use the default language to translate the diferents texts

this is how my app.component.ts works:

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


@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent implements OnInit {
  constructor(translate: TranslateService) {
    translate.addLangs(['es']);
    translate.setDefaultLang('es');

    const browserLang: string = translate.getBrowserLang();
    translate.use(browserLang.match(/en|es/) ? browserLang : 'es');
  }

  ngOnInit() {
  }

}

So the service use "en.json", "es.json" and "fr.json" to match the translation.

So my question is

How to avoid the "json" documents and match the texts with the text from the database?

So the client never have to been rebuild to get the new translation updates, just adding to the database and automatically translating without the rebuild

1 Answers

Ngx-translate has a method setTranslation that accepts the Lang key and a JSON object - you can load your JSON object from anywhere (eg: a database) and set them using this

setTranslation(lang: string, translations: Object, shouldMerge: boolean = false): Manually sets an object of translations for a given language, set shouldMerge to true if you want to append the translations instead of replacing them

Docs: https://github.com/ngx-translate/core/blob/master/README.md#api

Related