CodeurDuLundi
CodeurDuLundi

Reputation: 11

Angular/Ngx translate: display dynamically currentLang obtained from a server

I am making a project that allows to translate an application with the data on a server.

I created a Service to get the needed data:

@Injectable()
export class TranslationService {

  constructor(private http: HttpClient) { }

  getLangs(): Observable<string[]> {
    return this.http.get<string[]>(TRANSLATION_URL);
  }

  getDefaultLang(): Observable<string> {
    return this.http.get<string>(TRANSLATION_URL + '/defaultLang');
  }

  changeStartLang(lang: string) {
    this.http.post(TRANSLATION_URL + '/defaultLang', lang);
  }

}

getDefaultLang() returns a response with a body like this:

"en"

In app.component, I initialize the app with a defaultLang:

// get available langs from server and start language
      this.translationService.getLangs()
      .toPromise().then(langs => translate.addLangs(langs));
      translate.setDefaultLang('en');
      const browserLang = translate.getBrowserLang();
      this.translationService.getDefaultLang()
      .toPromise().then(lang => (lang !== null) ? this.translate.use(lang) : this.translate.use(browserLang));

In another component, i want to display the currentLang from TranslateService:

<div>{{'LANGUAGE.LANGUAGE_IN_USE' | translate}}</div>
<div (click)="changeLanguage()">{{translate.currentLang | uppercase}}</div>

The function changeLanguage() allows to switch between different languages.

When i open this component, i get undefined for currentLang and once i call the function changeLanguage(), the lang is well displayed.

How can i solve this?

Upvotes: 0

Views: 777

Answers (1)

CodeurDuLundi
CodeurDuLundi

Reputation: 11

Found the solution. Changed the response of the server to:

{ "lang": "en" }

With getDefaultLang():

getDefaultLang(): Observable<any> {
    return this.http.get(TRANSLATION_URL + '/defaultLang');
  }

And the code in app.component to:

const browserLang = translate.getBrowserLang();
      this.translationService.getDefaultLang()
      .toPromise().then(res => (res.lang !== null) ? this.translate.use(res.lang) : this.translate.use(browserLang))
      .catch(error => console.log(error));

And it solves all my problems, translate.currentLang is no longer undefined at launch.

Upvotes: 1

Related Questions