angular - ngOnInit() 中的 Angular Transloco 用法
问题描述
我知道下面的代码不起作用,因为翻译文件en.json
还没有加载,什么时候ngOnInit()
被调用:
组件.ts
ngOnInit() {
console.log(this.translocoService.translate('hello', { value: 'world' }););
}
en.json
{
"hello": "Hello",
}
另一种方法是订阅:
ngOnInit() {
this.translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => console.log(value));
}
但在我的组件中,我有 30 个键需要翻译。我真的应该订阅所有 30 个密钥吗?
演示: https ://stackblitz.com/edit/ngneat-transloco-8xqjqm?file=src%2Fapp%2Fapp.component.ts
解决方案
我认为您应该组织您的 JSON 翻译文件,使其具有包含组件所需的所有 30 种翻译的父属性(我们称之为父属性parentAttribute
,但要找到一个更好的名称;)):
{
"parentAttribute": {
"child1": "translation1"
...
"child30": "translation30"
}
}
然后,您应该使用transloco 服务提供的translateObject
方法:
const translations = this.translocoService.translateObject('parentAttribute');
translations
变量应包含:
{
"child1": "translation1"
...
"child30": "translation30"
}
推荐阅读
- javascript - $rootScope.$digest 正在清除参数
- javascript - 反应导航 - createBottomTabNavigator 不工作
- python - 使用 QsciScintilla.findNext 向后搜索未按预期工作
- python - Python - 拆分 xml 并添加原始根注释
- java - 在jsp中隐藏提交参数
- dynamic - webpack handlbars-loader:inlineRequires 不适用于动态路径
- php - Paypal 访问令牌每 1 小时过期一次
- angularjs - 如何在没有管理员权限的情况下检查 github 漏洞?
- powershell - 无法使用 PowerShell 脚本发送电子邮件
- java - 使用 maven 的 Netbeans 应用程序 9