I'm using ngx-translate
for doing my translations in my angular app, with use()
is working perfectly the problem is when I use the get(key)
method as is not returning the translated value, I have done some research and it seems to be an asynchronous problem as the get method is returning before I get the JSON
file with the translations, how can I solve this situation?
This is how my JSON
looks like
info: {
"EN": "English",
"ES": "Spanish",
"Register new device": "Registra un nuevo dispositivo",
...
}
Here is my app.module
export class CustomLoader implements TranslateLoader {
constructor(private http: HttpClient) {}
public getTranslation(lang: String){
return this.http.get(API_URL+'/getLanguage/'+lang+'.json', httpOptions)
}
}
@NgModule({
declarations: [
AppComponent
],
imports: [
...,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: CustomLoader,
deps: [HttpClient]
}
}),
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
]
})
Here is my service
where I use the methods from the library
import { TranslateService } from '@ngx-translate/core';
export class TranslateConfigService{
language:any;
constructor(private translateService:TranslateService){
this.language = JSON.parse(localStorage.getItem('language'))
if(!this.language)this.translateService.use('en');
else this.translateService.use(this.language);
}
changeLanguage(type:string) {
localStorage.setItem('language', JSON.stringify(type));
this.translateService.use(type);
}
getId(id){
return this.translateService.get(id)
}
}
Here is the function translateKey()
I have it in every component and which is subscribing to the get response
buttonLabel: string = 'Register new device';
language:any;
activeItem: string;
constructor(
private translateService: TranslateConfigService,
) {}
ngOnInit(): void {
this.language = JSON.parse(localStorage.getItem('language'))
if(!this.language)localStorage.setItem('language', JSON.stringify("en"));
this.activeItem = this.language;
this.translateKey();
}
changeLang(type:string){
this.setActiveItem(type)
this.translateService.changeLanguage(type);
}
translateKey(){
this.translateService.getId(this.buttonLabel)
.subscribe(
res => {
console.log(res)
this.buttonLabel = res
}
)
}
This is how I solve it, as all the translation information was inside a field that is called info
in the JSON, I only had to make the reference to the field when using the get
translateKey(langKey){
this.translateService.getId("info."+langKey)
.subscribe(
res => {
this.buttonLabel = res
}
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.