robisim74 / angular-l10n

Angular library to translate texts, dates and numbers
MIT License
380 stars 59 forks source link

feat(missing-translation-handler) - add third optional param to the "… #324

Closed dzena closed 3 years ago

dzena commented 3 years ago

…handle" method to accept option parameters contained in the translation key.

This will allow us to handle optional params in the missing translations if we want to fallback to a default language (the language we are sure all translations are up to date), something like this:

@Injectable()
export class MissingTranslation implements L10nMissingTranslationHandler {
    private translation: L10nTranslationService;

    constructor(@Optional() private injector: Injector) {}

    public handle(key: string, value?: string, params?: any): string | any {
        // avoid cyclic dependency
        this.translation = this.injector.get(L10nTranslationService);
        return this.translation.translate(key, params, 'en-US');
    }
}
robisim74 commented 3 years ago

Hi Milan,

thanks a lot for this PR! I'll release a new version by tonight.

Just a note: I think it's related to #279 , but it was only an example. I think you need a more robust handle, because if the key is not present even in the default language, you risk a loop:

    public handle(key: string, value?: string, params?: any): string | any {
        // avoid cyclic dependency
        this.translation = this.injector.get(L10nTranslationService);

        if (this.translation.has(key, 'en-US')) {
            return this.translation.translate(key, params, 'en-US');
        } else {
            return 'not found';
        }
    }

I must also suggest that you consider using (alternatively) a custom TranslationFallback: https://github.com/robisim74/angular-l10n#translation-fallback

Greetings

dzena commented 3 years ago

Hi Roberto,

Thanks for such an expedite response.

Also, really appreciate you suggestions. The reason I am not using TranslationFallback is that when I started with the lib (~2 years ago) it didn't work as expected and since then I never tried it anymore. I'll certainly give it another try.

Cheers.