robisim74 / angular-l10n

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

Empty string renders as missing translation #319

Closed ruisilva450 closed 3 years ago

ruisilva450 commented 3 years ago

Describe the bug I have a typical json being loaded by HttpTranslationLoader in which a token leads to an empty string on that json

To Reproduce Steps to reproduce the behavior:

  1. Have a return json that looks like this:
    {
    'textToTranslate': ''
    }
  2. Have a view that tries to translate 'textToTranslate'

Expected behavior See ` (basically show nothing) instead oftextToTranslate`

Desktop (please complete the following information):

Additional context You can reproduce this on the live demo. Here is the live demo with changeLocale value set as ""

ruisilva450 commented 3 years ago

As a workaround I did this:

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

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

  public handle(key: string): string | any {
    this.translation = this.injector.get(L10nTranslationService);

    const data = this.translation.data;

    let value = null;
    try {
      value = key.split('.').reduce((a, v) => a[v], data[this.translation.getLocale().language]);
    } catch {}

    if (value != null) {
      return value;
    }
    return key;
  }
}
robisim74 commented 3 years ago

Hi @ruisilva450,

In my opinion, an empty string is a missing translation.

But because this need has already been reported in the past, I will add value parameter to handle method, so everyone can handle it.

ruisilva450 commented 3 years ago

For some locales you can have a use case where you don't want to show certain information and the way some people do it is by putting an empty string.

Therefore my case

robisim74 commented 3 years ago

I released a new version (10.1.2). Now you should be able to do this:

@Injectable() export class AppMissingTranslationHandler implements L10nMissingTranslationHandler {

    public handle(key: string, value?: string): string | any {
        if (value !== null) return value;
        return key;
    }

}

Let me know.

ruisilva450 commented 3 years ago

Perfect.