Skip to content

Instantly share code, notes, and snippets.

@SandeepThomas
Last active November 14, 2018 10:47
Show Gist options
  • Save SandeepThomas/9341d0044e18372ef2088ea01d2e6808 to your computer and use it in GitHub Desktop.
Save SandeepThomas/9341d0044e18372ef2088ea01d2e6808 to your computer and use it in GitHub Desktop.
ngx translate custom loader
/*
* Custom Translate Loader to reload lang JSON on network failure
*/
import { TranslateLoader } from "@ngx-translate/core";
import { Injectable } from "@angular/core";
import { HttpHeaders, HttpClient } from "@angular/common/http";
import { ConnectionService } from ".";
import { Observable } from "rxjs";
import { filter, take } from "rxjs/operators";
@Injectable()
export class CustomTranslateLoader implements TranslateLoader {
private contentHeader = new HttpHeaders({ "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
constructor(private http: HttpClient, private connectionService: ConnectionService) {
}
getTranslation(lang: string): Observable<any> {
const apiAddress = "/locale/" + lang + ".json";
const callJSON = (observer) => {
this.connectionService.monitor()
.pipe(filter((isConnected: any) => isConnected), take(1))
.subscribe(() => {
this.http.get(apiAddress, { headers: this.contentHeader })
.subscribe((res: Response) => {
observer.next(res);
observer.complete();
}, (error) => {
callJSON(observer);
});
});
}
return Observable.create(observer => {
this.http.get(apiAddress, { headers: this.contentHeader })
.subscribe((res: Response) => {
observer.next(res);
observer.complete();
}, (error) => {
callJSON(observer);
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment