Angular ngx-translate TranslateLoader ohne http Modul


Compatibility with old browsers, as the Firefox version <= 5 to reach, can you do that angular http Do not use module. The NGX-translate Modules bneötigt a loader, It loads the correct language via AJAX request. Also with the XMLHttpRequest and an Observalbe solve this can:

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

@Injectable()
export class LanguageLoader implements TranslateLoader {

  getTranslation(lang: string): Observable<any> {
    return Observable.create(function (observer) {
    let url = `./assets/i18n/${lang}.json?=` + new Date().getTime();
    let xhr = new XMLHttpRequest();

      xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE || xhr.readyState == 4) {
              let response = JSON.parse(xhr.responseText);
              observer.next(response);
              observer.complete();
        }
      }
      xhr.open('GET', url, true);
      xhr.send(null);
    });
  }
}

In the app.module.TS can you then embed the loader as follows:

TranslateModule.forRoot({
  loader: {provide: TranslateLoader, useClass: LanguageLoader}
})

Comments are closed.