首页 > 解决方案 > 无法将 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);
}

标签: angulartypescript

解决方案


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>

是工作样本

结果:

在此处输入图像描述


推荐阅读