Skip to content

Commit 920b95d

Browse files
saithisocombe
authored andcommitted
fix(TranslateService): compile translations only once (#956)
Fixes #955
1 parent 99726a4 commit 920b95d

File tree

2 files changed

+37
-6
lines changed

2 files changed

+37
-6
lines changed

projects/ngx-translate/core/src/lib/translate.service.ts

+11-6
Original file line numberDiff line numberDiff line change
@@ -238,18 +238,23 @@ export class TranslateService {
238238
*/
239239
public getTranslation(lang: string): Observable<any> {
240240
this.pending = true;
241-
this.loadingTranslations = this.currentLoader.getTranslation(lang).pipe(share());
242-
243-
this.loadingTranslations.pipe(take(1))
241+
const loadingTranslations = this.currentLoader.getTranslation(lang).pipe(share());
242+
this.loadingTranslations = loadingTranslations.pipe(
243+
take(1),
244+
map((res: Object) => this.compiler.compileTranslations(res, lang)),
245+
share()
246+
);
247+
248+
this.loadingTranslations
244249
.subscribe((res: Object) => {
245-
this.translations[lang] = this.compiler.compileTranslations(res, lang);
250+
this.translations[lang] = res;
246251
this.updateLangs();
247252
this.pending = false;
248253
}, (err: any) => {
249254
this.pending = false;
250255
});
251256

252-
return this.loadingTranslations;
257+
return loadingTranslations;
253258
}
254259

255260
/**
@@ -369,7 +374,7 @@ export class TranslateService {
369374
observer.error(err);
370375
};
371376
this.loadingTranslations.subscribe((res: any) => {
372-
res = this.getParsedResult(this.compiler.compileTranslations(res, this.currentLang), key, interpolateParams);
377+
res = this.getParsedResult(res, key, interpolateParams);
373378
if (typeof res.subscribe === "function") {
374379
res.subscribe(onComplete, onError);
375380
} else {

projects/ngx-translate/core/tests/translate.service.spec.ts

+26
Original file line numberDiff line numberDiff line change
@@ -406,4 +406,30 @@ describe('TranslateService', () => {
406406

407407
expect(getTranslationCalls).toEqual(1);
408408
}));
409+
410+
it('should compile translations only once, even when subscribing to translations while translations are loading', fakeAsync(() => {
411+
spyOn(translate.currentLoader, 'getTranslation').and.callFake(() => {
412+
return timer(1000).pipe(mapTo(of(translations)));
413+
});
414+
415+
let translateCompilerCallCount = 0;
416+
spyOn(translate.compiler, 'compile').and.callFake((value) => {
417+
++translateCompilerCallCount;
418+
return value;
419+
});
420+
spyOn(translate.compiler, 'compileTranslations').and.callFake((value) => {
421+
++translateCompilerCallCount;
422+
return value;
423+
});
424+
425+
translate.setDefaultLang('en-US');
426+
translate.get('TEST1').subscribe();
427+
translate.get('TEST2').subscribe();
428+
translate.get('TEST3').subscribe();
429+
translate.get('TEST4').subscribe();
430+
431+
tick(1001);
432+
433+
expect(translateCompilerCallCount).toBe(1);
434+
}));
409435
});

0 commit comments

Comments
 (0)