jsverse / transloco

🚀 😍 The internationalization (i18n) library for Angular
https://jsverse.github.io/transloco/
MIT License
1.97k stars 191 forks source link

Feature(transloco): allow option to disable loading language files at root i18n level #732

Open jdiemke opened 6 months ago

jdiemke commented 6 months ago

Is there an existing issue for this?

Which Transloco package(s) will this feature affect?

Transloco

Is your feature request related to a problem? Please describe

When using only scoped translations at standalone component level, then there might be no need to load unscoped translations at the root level since these translation files can be empty. In this case it makes sense to have the possibility to disable loading translations at root level "assets/i18n/{{lang}}.json".

Describe the solution you'd like

Provide a transloco config flag that disables the initial loading of unscoped translations or provide another signature for getTranslation method of the TranslocoLoader that does not contain the scope as part of the lang parameter. Instead provide a separate data parameter that is always available. Then the loader should ne able to contruct the url itself from lang and scope:

 public getTranslation(lang: string, data: TranslocoLoaderData): Observable<Translation> {
   if (!data.scope) {
      return of({});
    }
    return this.http.get<Translation>(`/assets/i18n/${data.scope}/${lang}.json`);
  }

This would allow to write a custom loader that only loads using http when a scope is available. But an additional config flag would still make sense so the scope check could be removed in the TranslocoLoader

Describe alternatives you've considered

I wrote a custlom loader that checks wether the data object is undefined. I think the design flaw in the custom loader class is that the language parameter can be a language string or a string containing a language with a scoped prefix and it is not easy to distinguish between both without further knowlegde. In addition it is a bit surprising, that a parameter called lang can also include a scope prefix.

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {

  private http = inject(HttpClient);

  public getTranslation(lang: string, data?: TranslocoLoaderData): Observable<Translation> {

    if (!this.hasScope(data)) {
      return of({});
    }

    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }

  private hasScope(data?: TranslocoLoaderData): boolean {
    return data !== undefined;
  }

}

Additional context

No response

I would like to make a pull request for this feature

No

gtteamamxx commented 1 month ago

Similar situation here.

I've many scopes, but root translation files are just empty. It's because transloco not working without it. I'm operating only via scoped translations.

image