Skip to content

Commit

Permalink
Add ability to dynamically add translation asset paths
Browse files Browse the repository at this point in the history
  • Loading branch information
bameyrick committed Jan 30, 2025
1 parent ff8ea6e commit a337c76
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 4 deletions.
43 changes: 42 additions & 1 deletion packages/ng-lazy-translate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,22 @@ Lazy loaded translation module for Angular using [messageformat](https://message
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=bameyrick_ng-lazy-translate&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=bameyrick_ng-lazy-translate)
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=bameyrick_ng-lazy-translate&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=bameyrick_ng-lazy-translate)

- [@qntm-code/ng-lazy-translate](#qntm-codeng-lazy-translate)
- [Installation](#installation)
- [Usage - Standalone Components](#usage---standalone-components)
- [1. Create providers](#1-create-providers)
- [Usage - Within a Module](#usage---within-a-module)
- [1. Import Module](#1-import-module)
- [2. Import module in component](#2-import-module-in-component)
- [Using pipe in a template](#using-pipe-in-a-template)
- [Using the service in a component/service](#using-the-service-in-a-componentservice)
- [Dynamically adding translation asset paths](#dynamically-adding-translation-asset-paths)
- [LazyTranslateModuleConfig](#lazytranslatemoduleconfig)
- [Language](#language)
- [TranslationAssetPaths](#translationassetpaths)
- [Translation files](#translation-files)
- [Default value](#default-value)

## Installation

```bash
Expand Down Expand Up @@ -134,6 +150,31 @@ export class MyService {
}
```

## Dynamically adding translation asset paths

You can dynamically add translation asset paths by calling the `addTranslationAssetPaths` method on the `LazyTranslateService`:

```typescript
import { LazyTranslateService } from '@qntm-code/ng-lazy-translate';

export const appRoutes: Route[] = [
{
path: '',
loadChildren: () =>
import('./home/home.module').then(({ HomeModule }) => {
const translateService = inject(LazyTranslateService);

translateService.addTranslationAssetPaths({
'en.home': 'assets/i18n/en/home.json',
'fr.home': 'assets/i18n/fr/home.json',
});

return HomeModule;
}),
},
];
```

## LazyTranslateModuleConfig

Whether you use the standalone components or the module, the LazyTranslateModuleConfig options are the same.
Expand All @@ -142,7 +183,7 @@ Whether you use the standalone components or the module, the LazyTranslateModule
| ------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------- |
| defaultLanguage | string | The default language to use if no language is specified | Yes | N/A |
| languages | [Language[]](#language) | The list of languages to support | Yes | N/A |
| translationAssetPaths | [TranslationAssetPaths](#translationassetpaths) | The list of translation assets to load. The key is the language and the translation file name. | Yes | N/A |
| translationAssetPaths | [TranslationAssetPaths](#translationassetpaths) | The list of translation assets to load. The key is the language and the translation file name. | No | N/A |
| useDefaultLanguage | boolean | Whether to use the default language if the specified language is not found | No | `true` |
| enableLogging | boolean | Whether to enable logging of missing translations | No | `true` |
| missingTranslationHandler | (language: string, key: string) => void | A custom handler to use when a translation is not found. If not specified, the default handler will be used. | No | Will console.error a message |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { TranslationAssetPaths } from './translation-asset-paths.model';
export interface LazyTranslateModuleConfig {
languages: Language[];
defaultLanguage: string;
translationAssetPaths: TranslationAssetPaths;
translationAssetPaths?: TranslationAssetPaths;
useDefaultLanguage?: boolean;
enableLogging?: boolean;
missingTranslationHandler?: MissingTranslationHandlerFn;
Expand Down
19 changes: 17 additions & 2 deletions packages/ng-lazy-translate/src/lib/translate.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
shareReplay,
withLatestFrom,
} from 'rxjs';
import { LazyTranslateModuleConfig } from './models';
import { LazyTranslateModuleConfig, TranslationAssetPaths } from './models';
import { NG_LAZY_TRANSLATE_CONFIG } from './tokens';

@Injectable()
Expand Down Expand Up @@ -51,9 +51,15 @@ export class LazyTranslateService {
*/
private readonly config: LazyTranslateModuleConfig;

private readonly translationAssetPaths = new Map<string, string>();

constructor(@Inject(NG_LAZY_TRANSLATE_CONFIG) config: LazyTranslateModuleConfig, private readonly http: HttpClient) {
this.config = { useDefaultLanguage: true, enableLogging: true, ...config };

if (this.config.translationAssetPaths) {
this.addTranslationPaths(this.config.translationAssetPaths);
}

this.defaultLanguage$ = new BehaviorSubject<string>(this.config.defaultLanguage);

this.language$ = new BehaviorSubject<string>(
Expand All @@ -73,6 +79,13 @@ export class LazyTranslateService {
}
}

/**
* Adds translation asset paths
*/
public addTranslationPaths(paths: TranslationAssetPaths): void {
Object.entries(paths).forEach(([key, value]) => this.translationAssetPaths.set(key, value));
}

public setLanguage(language: string): void {
this.language$.next(this.getValidLanguageCode(language));
}
Expand Down Expand Up @@ -167,14 +180,16 @@ export class LazyTranslateService {
* Downloads a language file for a given namespace
*/
private downloadFile(language: string, namespace: string): Observable<Record<string, unknown> | undefined> {
const path = this.config.translationAssetPaths[`${language}.${namespace}`];
const path = this.translationAssetPaths.get(`${language}.${namespace}`);

if (!path) {
if (this.config.missingFileHandler) {
this.config.missingFileHandler(namespace, language);
} else if (this.config.enableLogging) {
console.error(`File with namespace ${namespace} not found for language ${language}`);
}

return of(undefined);
}

let observable = this.downloadedRequests[path];
Expand Down

0 comments on commit a337c76

Please sign in to comment.