Skip to content
This repository was archived by the owner on Nov 8, 2021. It is now read-only.

Commit f0ade9c

Browse files
author
baso10
committed
Load translations with promise, to allow loading before app is initialized
1 parent 4f95eb6 commit f0ade9c

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/http-loader.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import {HttpClient} from "@angular/common/http";
22
import {TranslateLoader} from "@ngx-translate/core";
3+
import {Observable} from 'rxjs/Rx';
34

45
export class TranslateHttpLoader implements TranslateLoader {
6+
loadedTranslations: { [index: string]: Object; } = {};
7+
58
constructor(private http: HttpClient, public prefix: string = "/assets/i18n/", public suffix: string = ".json") {}
69

710
/**
@@ -10,6 +13,27 @@ export class TranslateHttpLoader implements TranslateLoader {
1013
* @returns {any}
1114
*/
1215
public getTranslation(lang: string): any {
13-
return this.http.get(`${this.prefix}${lang}${this.suffix}`);
16+
if (this.loadedTranslations != null && this.loadedTranslations[lang] != null) {
17+
return Observable.of(this.loadedTranslations[lang]);
18+
}
19+
return Observable.fromPromise(this.preLoad(lang));
20+
}
21+
22+
/**
23+
* Gets the translations from the server as Promise
24+
* @param lang
25+
* @returns Promise<any>
26+
*/
27+
public preLoad(lang: string): Promise<any> {
28+
return new Promise((resolve, reject) => {
29+
this.http.get(`${this.prefix}${lang}${this.suffix}`)
30+
.catch((error: any): any => {
31+
resolve(null);
32+
})
33+
.subscribe((result) => {
34+
this.loadedTranslations[lang] = result;
35+
resolve(result);
36+
});
37+
});
1438
}
1539
}

0 commit comments

Comments
 (0)