Search code examples
angularinternationalizationtranslationngx-translate

Angular translation service sometimes doesn't work


I have a project using Angular 16.1.1, where I need to translate some words in TypeScript code. I'm using ngx-translate and I have written the following code:

constructor(public translate: TranslateService) { this.setTranslation(); }

setTranslation(): void {
    this.translate.use('en-US');

    this.translate.get('Example').subscribe(ex => {
        this.foo = this.translate.instant(ex);

        this.bar = this.translate.instant('Anything'); 

        console.log(this.foo + ' ' + this.bar);

    });
}

My problem is that this code sometimes translate the tags properly and sometimes doesn't. I've noticed that if I add a delay after this.translate.use('en-US'), the code works 95% of the time, but when I load the page with a slower internet connection, it still doesn't work.

I think the TranslateService relies on HTTP requests, which might be why it only works sometimes.

How can I solve this?

EDIT: I noticed that the problem is that sometimes when I call translate.use and then translate.get, it seems that the language is not updated in time and the translation takes place based on the previously set language


Solution

  • UPDATE:

    According to the ngx-translate/core github, the use method returns an observable, so you need to first execute the observable, then switch to the inner observable using switchMap, finally execute the logic in the subscribe.

    constructor(public translate: TranslateService) { this.setTranslation(); }
    
    setTranslation(): void {
        this.translate.use('en-US').pipe(
            switchMap(() => this.translate.get('Example')),
        ).subscribe(ex => {
            this.foo = this.translate.instant(ex);
    
            this.bar = this.translate.instant('Anything'); 
            console.log(this.foo + ' ' + this.bar);
        });
        
    }
    

    The code inside the subscribe, does not wait for the code below the subscribe, since the first is asynchronous and the bottom is synchronous, so you need to move the code inside the subscribe, to get consistent results.

    Synchronous vs Asynchronous JavaScript – Call Stack, Promises, and More