angular - 无法将 undefined 或 null 转换为对象 Angular
问题描述
我尝试制作一个过滤方法,这种方法效果很好,但我有一个错误:cannot convert undefined or null to object that I cannot solve
示例 json
{
"toto": [
"titi",
"tata"
],
hideString: [], // filter method hide this element
"foo": [
"foobar",
"footix"
]
}
卡片组件.ts
@Input() toto: ISummary[] = []
getKeys() {
Object.keys(this.toto).filter(key => this.toto[key].lenght > 0)
// in my console I have the following error: cannot convert undefined or null to object
the error comes from this line
}
totoa(keys:string){
return this.toto[key]
}
卡片.html
<div *ngFor="let keys of getKeys()">
{{keys}}
<div *ngFor="let values of totoa(keys)">
{{values}}
</div
</div
主页.components.ts
public result: string = '';
public toto?: Observable<ISummary[]>; // maybe the problem comes from Here I have ternary operator '?'
ngOnInit() {
this.activatedRoute.paramMap.subscribe(params = > {
let bigramme = params.get('bigramme');
this.result = bigramme as string;
getSummary();
}
}
getSummary() {
this.toto = this.sumService.getAllSummary(this.result);
}
解决方案
cannot convert undefined or null to object Angular
尝试时发生Object.keys(null)
错误。因此,您可以检查要传递给的对象object.keys
。
但
看来您想在 html 中显示一些基于 的数据key/value
,因此为此目的有一个keyvalue
管道,不需要额外的代码,例如totoa
方法。
为了隐藏空值,只需使用[hidden]
<div *ngFor="let item of testObject | keyvalue" [hidden]="item.value.length == 0">
Key: <b>{{item.key}}</b>
<div *ngFor="let item1 of item.value">
Value: <b>{{item1}}</b>
</div>
<br>
</div>
这是工作样本
结果:
推荐阅读
- wordpress - 编辑器中的垂直对齐,Smart Slider 3 Wordpress
- javascript - 如何修复 jshint 错误预期 '(' 在 '(' 之前。(expected_a_before_b)
- javascript - 在 ASP.NET MVC 4.5 中使用引导程序 4.1 创建模式
- git - 稀疏结帐在工作目录上没有留下任何条目
- sql - tSQLt.ExceptionException 不适用于 SQL Server 中的回滚事务
- sql - 加入2张桌子的最佳方式是什么?
- arduino - 退出状态 1 'class WiFiClass' 在 NodeMCU 中没有名为“softAP”的成员
- mysql - 如何更新所有引用约束中的 MySQL 字段长度?
- mongodb - AWS Database Migration Service (DMS) MongoDB 到 S3 中的 CSV
- r - 在分组条形图中设置变量的顺序