robisim74 / angular-l10n

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

Setting available languages from Database #334

Closed leonxger closed 1 year ago

leonxger commented 2 years ago

Hello, first of all, thank you for this amazing libary!

My question is the following: I think, normally you set the available languages for your application in the schema of the l10n-config.ts file.

image

What i want: I have a service for my backend to load the available languages from the database. I use my own datamodel for this which has the following properties: languageID, languageCode and name. Supposing that we dont need currency and timezone, i can now easily convert my datamodel to a L10nSchema.

My Problem: Since the l10nConfig is an constant, im now trying to figure out how to set the schemas after my available languages are loaded from the backend. Is this even the right place to do it?

In short words: Normally the available languages are set initially in the l10n-config.ts file, but i wanna set them after i loaded them from my backend.

Thank you in advance!

robisim74 commented 2 years ago

Hi @leonxger ,

l10nConfig is stored into an Injection token, so you can access it through Dependency Injection:

@Inject(L10N_CONFIG) private l10nConfig: L10nConfig

After you have uploaded your schema from the server, you can update it directly:

this.l10nConfig.schema = [...];

Try this way and let me know if you run into any problems.

leonxger commented 2 years ago

Thank you very much for the solution!

robisim74 commented 2 years ago

Just released a new version of the library to provide a more robust solution. Now you can implement the L10nLoader class-interface to preload the data before the initialization of the library:

@Injectable() export class AppLoader implements L10nLoader {

    constructor(private translation: L10nTranslationService, @Inject(L10N_CONFIG) private config: L10nConfig) { }

    public async init(): Promise<void> {
        await new Promise((resolve) => {
            // Just an example of delayed data
            setTimeout(() => {
                this.config.schema = [
                    { locale: { language: 'en-US', currency: 'USD', timeZone: 'America/Los_Angeles', units: { 'length': 'mile' } }, dir: 'ltr', text: 'United States' },
                    { locale: { language: 'it-IT', currency: 'EUR', timeZone: 'Europe/Rome', units: { 'length': 'kilometer' } }, dir: 'ltr', text: 'Italia' }
                ];
                resolve(null);
            }, 1000);
        });
        await this.translation.init();
    }
}

@NgModule({
    imports: [
        L10nTranslationModule.forRoot(
            l10nConfig,
            {
                loader: AppLoader
            }
        ),
    ],
})

See also https://github.com/robisim74/angular-l10n#loader

leonxger commented 2 years ago

Thanks for your effort! :-)

robisim74 commented 1 year ago

Closed due to inactivity