Skip to content

Commit

Permalink
fix(TranslateService): only make one request per lang
Browse files Browse the repository at this point in the history
This stops multiple requests being made for the same lang file. It will now return the same observable when making duplicate requests for the same language.

Fixes #397
Fixes #432 
Fixes #447
Fixes Greentube/localize-router#26
Fixes #462
  • Loading branch information
deeg authored and ocombe committed Mar 23, 2017
1 parent 55fbc41 commit 6427a47
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/translate.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export class TranslateService {
private _currentLang: string;
private _langs: Array<string> = [];
private _translations: any = {};
private _translationRequests: any = {};

/**
* An EventEmitter to listen to translation change events
Expand Down Expand Up @@ -230,7 +231,8 @@ export class TranslateService {

// if this language is unavailable, ask for it
if(typeof this.translations[lang] === "undefined") {
pending = this.getTranslation(lang);
this._translationRequests[lang] = this._translationRequests[lang] || this.getTranslation(lang);
pending = this._translationRequests[lang];
}

return pending;
Expand Down Expand Up @@ -475,6 +477,7 @@ export class TranslateService {
* @param lang
*/
public resetLang(lang: string): void {
this._translationRequests[lang] = undefined;
this.translations[lang] = undefined;
}

Expand Down
16 changes: 15 additions & 1 deletion tests/translate.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Injector} from "@angular/core";
import {TranslateService, TranslateLoader, LangChangeEvent, TranslationChangeEvent, TranslateModule} from '../index';
import {Observable} from "rxjs/Observable";
import {getTestBed, TestBed} from "@angular/core/testing";
import {getTestBed, TestBed, fakeAsync, tick} from "@angular/core/testing";

let translations: any = {"TEST": "This is a test"};
class FakeLoader implements TranslateLoader {
Expand Down Expand Up @@ -296,4 +296,18 @@ describe('TranslateService', () => {
expect(browserCultureLand).toBeDefined();
expect(typeof browserCultureLand === 'string').toBeTruthy();
});

it('should not make duplicate requests', fakeAsync(() => {
let getTranslationCalls = 0;
spyOn(translate.currentLoader, 'getTranslation').and.callFake(() => {
getTranslationCalls += 1;
return Observable.timer(1000).mapTo(Observable.of(translations));
});
translate.use('en');
translate.use('en');

tick(1001);

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

0 comments on commit 6427a47

Please sign in to comment.