Search code examples
angularngx-translate

NGX-Translate how not to get 404?


I'm using NGX-Translate on my Angular Application and even thou the translations works, I only have translation for 3 languages (en-CA, pt-BR, en-US). This is how I'm setting the language:

const defaultLanguage = translate.getBrowserCultureLang();
translate.setDefaultLang(defaultLanguage);

Here is the issue, is the browser's culture language is set to "fr-CA" for example, I get a 404 error saying it couldn't find the fr-CA.json file. Which is correct because that file doesn't exist. Is there a way not to have that 404? Or do I have to have a file for every single language and culture?


Solution

  • Think that you have to implement a custom TranslateLoader as mentioned in this GitHub issue.

    This LazyTranslateLoader will send the request to fetch the JSON file for the current language. In case the response returned is not successful, it will fetch the JSON file for the default language.

    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    import { Observable } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    export const DEFAULT_LANG = 'en-US';
    export class LazyTranslateLoader implements TranslateLoader {
      constructor(private http: HttpClient) {}
    
      getTranslation(lang: string): Observable<any> {
        return this.http
          .get(`/assets/i18n/${lang}.json`)
          .pipe(
            catchError(() => this.http.get(`/assets/i18n/${DEFAULT_LANG}.json`))
          );
      }
    }
    

    Next, provide the LazyTranslateLoader in the configuration for TranslateModule located in your root module.

    @NgModule({
      // ...,
      imports: [
        // ...,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: LazyTranslateLoader,
            deps: [HttpClient],
          },
        }),
      ]
    })
    export class AppModule {}
    

    Demo @ StackBlitz


    Reference

    Write & use your own loader