Skip to content

Commit

Permalink
fix: lazily resolve translate service in translate compiler (#978)
Browse files Browse the repository at this point in the history
Co-authored-by: max.kless@googlemail.com <max.kless@googlemail.com>
  • Loading branch information
2 people authored and SGrueber committed Feb 15, 2022
1 parent cb56168 commit 25866c5
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/app/core/utils/translate/pwa-translate-compiler.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { Injectable, Injector, isDevMode } from '@angular/core';
import { TranslateCompiler, TranslateService } from '@ngx-translate/core';
import { once } from 'lodash-es';

import { Translations } from './translations.type';

const cache: Record<string, Function> = {};

@Injectable()
export class PWATranslateCompiler implements TranslateCompiler {
constructor(private injector: Injector) {}

private static MAX_COMPILATION_LENGTH = 1000;

/**
Expand Down Expand Up @@ -52,6 +51,13 @@ export class PWATranslateCompiler implements TranslateCompiler {
*/
private static SIMPLE_VARIABLE_REGEX = /\{\{\s*(\w+)\s*\}\}/g;

private translate: () => TranslateService;

constructor(injector: Injector) {
// cache TranslateService reference to avoid repeated calls to injector
this.translate = once(() => injector.get(TranslateService));
}

private checkIfCompileNeeded(value: string | Function): boolean {
return (
typeof value === 'string' &&
Expand Down Expand Up @@ -105,7 +111,7 @@ export class PWATranslateCompiler implements TranslateCompiler {
if (rename) {
args[rename] = args[variable];
}
const delegate = this.injector.get(TranslateService).instant(key, args);
const delegate = this.translate().instant(key, args);
const result = `${match[1]}${delegate}${match[4]}`;

return this.recurse(result, args);
Expand Down Expand Up @@ -140,6 +146,9 @@ export class PWATranslateCompiler implements TranslateCompiler {
}

compileTranslations(translations: Translations): Translations {
// be sure translate dependency is initialized on the first run
this.translate();

// This implementation is mutable by intention
// eslint-disable-next-line guard-for-in
for (const key in translations) {
Expand Down

0 comments on commit 25866c5

Please sign in to comment.