[英]How to use TranslateHttpLoader with service url in ngx-translate
[英]Use ngx-translate in component
我在視圖中使用 ngx-translate 沒有問題,使用管道。 我需要做的是在組件中使用它,例如顯示錯誤消息,或定義數據表列的默認內容。
我正在嘗試做類似的事情:
translate.instant("AREA.NEW");
或者
translate.get("AREA.NEW").subscribe((res: string) => {
console.log(res);
});
我試過在 ngOnInit() 和 ngAfterViewInit() 中調用它
但在這兩種情況下,我都只得到“AREA.NEW”,而不是翻譯后的詞。 我假設 json 字典是在我打電話后加載的,所以我不知道它是如何工作的。
導入TranslateService並在您想要的任何地方使用它。
import { TranslateService } from '@ngx-translate/core';
export class YourComponent {
constructor(private translateService: TranslateService) {
console.log('translation', this.translateService.instant('my_i18n_json_defined_key'));
}
}
這是工作。
constructor(private readonly translateService: TranslateService) { }
ngOnInit() {
this.translateService.get(['']).subscribe(translations => {
console.info(this.translateService.instant('key1'));
console.info(this.translateService.instant('key2'));
console.info(this.translateService.instant('key3'));
});
}
“即時”翻譯不起作用的另一個原因可能是翻譯在需要時不可用。 當使用以異步方式從翻譯文件加載的 TranslateHttpLoader(此處示例)加載翻譯時,可能會發生這種情況。
此處顯示了克服此問題的一個技巧(剛剛測試並在 Angular 13+ 中工作)並通過在其路由上添加一個特殊的解析器強制組件等待直到轉換准備就緒:
@Injectable()
export class TranslationLoaderResolver {
constructor(private translate: TranslateService){ }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>{
return this.translate.get("does.not.matter");
}
}
{path: "segment", component: YourComponent, resolve: {model: TranslationLoaderResolver}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.