You can use TranslateService only when translation file is loaded.
If you want to use safely TranslateService.instant you can write an angular resolver or a guard.
Resolver and guard wait to exec your component code until the observable return a value.
This is the code:
-------------------------GUARD------------------------------------
@Injectable()
export class TranslationLoaderGuard {
constructor(private translate: TranslateService, private languageService: SetLanguageService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
this.languageService.inizializeLanguage()
return new Observable((observer) => {
this.translate.get("last.dummy").subscribe({
next: () => {
observer.next(true);
},
error: error => {
observer.next(false);
observer.error(error);
},
complete: () => {
observer.complete();
},
})
})
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
this.languageService.inizializeLanguage()
return new Observable((observer) => {
this.translate.get("last.dummy").subscribe({
next: () => {
observer.next(true);
},
error: error => {
observer.next(false);
observer.error(error);
},
complete: () => {
observer.complete();
},
})
})
}
}
---------------------ROUTING MODULE------------------
let routing = RouterModule.forChild([
{path: "dashboard", component: DashboardComponent, canActivate: [TranslationLoaderGuard],,
children: [
........//here you can omit Guard
},
}
-----Files i18n-----
In last line of each i18n translation file add the following line
as is (do not translate this) ----> "last.dummy"="dummy translation"
SetLanguageService
is a service that you can create to store the language used, for example in session storage (for example lang is 'it', 'en').
I hope this can help
.instant()
by.stream()
it's work for me – Eatthis.translateService.stream(event['title']) .subscribe((title) => this.titleService.setTitle(title))
– Eat.get()
,.instant()
and.stream()
functions are similar, please check this doc: github.com/ngx-translate/core; – Eat