ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.53k stars 579 forks source link

How to handle missing translation files of TranslateLoader? #1002

Open ivanastefanoska opened 5 years ago

ivanastefanoska commented 5 years ago

Current behavior

When translation file is missing on the specified path for TranslateHttpLoader, a console error is thrown reporting that file is not found.

Expected behavior

In case of missing translation file, I want to be able to use the default language.

How do you think that we should fix this?

Use 'useDefaultLang' property as a fallback for using default language in case of missing translation file, not only when localization string is missing.

Minimal reproduction of the problem with instructions

This is the error I got in console on selection language change, if transaltion file is missing for the selected language: image

Environment


ngx-translate/core version: ^10.0.2
ngx-translate/http-loader: ^3.0.1
Angular version: 6


sagrawal31 commented 5 years ago

Any workaround to this problem?

bitbaggi commented 5 years ago

You can add empty files for all supported languages. or you can subscribe languageChangeEvent on error from TranslateService and call use(service.getDefaultLang()).

alex7egli commented 5 years ago

@bitbaggi I tried that but they don't catch any errors on their subscribe call to get the language translation, so even if you subscribe to the error event of onLangChange you don't get anything. Currently I don't see anyway to handle this case except keeping an internal list of supported languages, or writing a file system check of the assets/i18n folder to check for the language file before setting to the browser language.

micrac commented 3 years ago

You can ovveride TranslateHttpLoader behaviour in the follwing way:

export class MyTranslateHttpLoader extends TranslateHttpLoader {

    defaultLocale: string;

    constructor(defaultLocale: string, http: HttpClient, prefix?: string, suffix?: string) {
        super(http, prefix, suffix);
        this.defaultLocale = defaultLocale;
    }

    getTranslation(lang: string) : Observable<Object> {
        return super.getTranslation(lang).pipe(
            catchError(err => {
                console.log(`Locale ${lang} not supproted, using default ${this.defaultLocale}`);
                return super.getTranslation(this.defaultLocale);
            })
        );
    }
}

Then use it instead of original one.