I want to use ngx-translate in my frontend to dynamically load translations on app load.
My backend returns a response in JSON format, ex:
{
"something: "something"
}
I want to use that output on my TranslateLoader instead of a local en.json
file.
Is there any way to achieve that?
TL;DL: I want to call 'http://localhost:xxxx/api/translation/EN' to get a JSON response of the translations and load it on TranslateHttpLoader
You can create a factory:
export function httpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, "http://localhost:xxxx/api/translation/", "");
}
And use it in your @NgModule imports:
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: httpLoaderFactory,
deps: [HttpClient]
}
}),
We can achieve using TranslateLoader provider with Custom Loader Class
In Module :
export class CustomLoader implements TranslateLoader {
constructor(private http: Http) {}
public getTranslation(lang: String): Observable<any> {
return this.http.get(URL).map(
(res: any) => {
return res;
}
);
}
}
@NgModule({
imports: [
TranslateModule.forRoot({
provide: TranslateLoader,
useClass: CustomLoader,
// useFactory: (createTranslateLoader),
deps: [Http]
})
]
})
In Component:
constructor(private _translate: TranslateService){}
const transText = this._translate.instant('something');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With