Skip to content

Commit

Permalink
fix(TranslateService): compile translations only once (#956)
Browse files Browse the repository at this point in the history
Fixes #955
  • Loading branch information
saithis authored and ocombe committed Nov 14, 2018
1 parent 99726a4 commit 920b95d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
17 changes: 11 additions & 6 deletions projects/ngx-translate/core/src/lib/translate.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,18 +238,23 @@ export class TranslateService {
*/
public getTranslation(lang: string): Observable<any> {
this.pending = true;
this.loadingTranslations = this.currentLoader.getTranslation(lang).pipe(share());

this.loadingTranslations.pipe(take(1))
const loadingTranslations = this.currentLoader.getTranslation(lang).pipe(share());
this.loadingTranslations = loadingTranslations.pipe(
take(1),
map((res: Object) => this.compiler.compileTranslations(res, lang)),
share()
);

this.loadingTranslations
.subscribe((res: Object) => {
this.translations[lang] = this.compiler.compileTranslations(res, lang);
this.translations[lang] = res;
this.updateLangs();
this.pending = false;
}, (err: any) => {
this.pending = false;
});

return this.loadingTranslations;
return loadingTranslations;
}

/**
Expand Down Expand Up @@ -369,7 +374,7 @@ export class TranslateService {
observer.error(err);
};
this.loadingTranslations.subscribe((res: any) => {
res = this.getParsedResult(this.compiler.compileTranslations(res, this.currentLang), key, interpolateParams);
res = this.getParsedResult(res, key, interpolateParams);
if (typeof res.subscribe === "function") {
res.subscribe(onComplete, onError);
} else {
Expand Down
26 changes: 26 additions & 0 deletions projects/ngx-translate/core/tests/translate.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,4 +406,30 @@ describe('TranslateService', () => {

expect(getTranslationCalls).toEqual(1);
}));

it('should compile translations only once, even when subscribing to translations while translations are loading', fakeAsync(() => {
spyOn(translate.currentLoader, 'getTranslation').and.callFake(() => {
return timer(1000).pipe(mapTo(of(translations)));
});

let translateCompilerCallCount = 0;
spyOn(translate.compiler, 'compile').and.callFake((value) => {
++translateCompilerCallCount;
return value;
});
spyOn(translate.compiler, 'compileTranslations').and.callFake((value) => {
++translateCompilerCallCount;
return value;
});

translate.setDefaultLang('en-US');
translate.get('TEST1').subscribe();
translate.get('TEST2').subscribe();
translate.get('TEST3').subscribe();
translate.get('TEST4').subscribe();

tick(1001);

expect(translateCompilerCallCount).toBe(1);
}));
});

0 comments on commit 920b95d

Please sign in to comment.