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

Commit 714e88f

Browse files
author
baso10
committed
Load translations with promise, to allow loading before app is initialized
1 parent 783d58e commit 714e88f

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,8 +1,11 @@
11
import {HttpClient} from "@angular/common/http";
22
import {TranslateLoader} from "@ngx-translate/core";
33
import "rxjs/add/operator/map";
4+
import {Observable} from 'rxjs/Rx';
45

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

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

0 commit comments

Comments
 (0)