Angular遍历i18n JSON对象失败,keyvalue管道未被识别求助
解决方案
1. 确保导入CommonModule
keyvalue管道属于Angular的CommonModule,如果当前组件所在的模块未导入它,就会出现管道未识别的错误。在你的模块文件中添加导入:
import { CommonModule } from '@angular/common'; import { TranslateModule } from '@ngx-translate/core'; @NgModule({ imports: [ CommonModule, // 必须导入才能使用keyvalue管道 TranslateModule ], declarations: [YourComponent] }) export class YourComponentModule { }
2. 修正模板中的管道使用
需要确保translate管道先执行,返回ST01P01.warranties对应的对象后,再用keyvalue管道遍历。给translate部分加上括号明确执行顺序:
<div *ngFor="let item of ('ST01P01.warranties' | translate) | keyvalue"> {{item.key}}: {{item.value}} </div>
3. 备选方案:在组件中预获取翻译对象
如果模板中管道嵌套容易出问题,可以在组件类中通过TranslateService提前获取翻译后的对象,再在模板中遍历:
import { Component, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent implements OnInit { warranties: Record<string, string> | null = null; constructor(private translate: TranslateService) {} ngOnInit(): void { this.translate.get('ST01P01.warranties').subscribe(data => { this.warranties = data; }); } }
模板代码:
<div *ngFor="let item of warranties | keyvalue" *ngIf="warranties"> {{item.key}}: {{item.value}} </div>
额外检查点
- 确认i18n JSON文件结构正确,
ST01P01.warranties确实是一个对象,而非字符串。 - 确保
@ngx-translate/core和@ngx-translate/http-loader已正确安装并配置。
内容的提问来源于stack exchange,提问作者Olivier
相关产品推荐
相关产品推荐

