Angular绑定API返回数据时*ngFor报不支持非可迭代对象错误
问题描述
调用API接口绑定列表数据时,浏览器网络面板可查看到接口正常返回数组格式数据,但页面渲染时抛出如下错误:
Cannot find a differ supporting object '[object Object]' of type 'function'. NgFor only supports binding to Iterables such as Arrays.
接口返回数据(网络面板抓取结果)
[{deliveryid: 0, frequency: "", ContactName: "Aa", Email: "aa@we.com",…},…] // 单条数据结构 {deliveryid: 0, frequency: "", ContactName: "Aa", Email: "aa@we.com"}
问题相关代码
TS逻辑代码
public MyDigestEmailIdPrint = []; DigestEmailIdPrint() { var postData = { clientid: localStorage.getItem("storageselectedclient"), }; this.article.DigestEmailIdPrint(postData).subscribe( (res) => { if (res.message != "No Record Found") { this.MyDigestEmailIdPrint.push(res); } }, (err) => { console.log(err); } ); }
HTML模板代码
<tbody> <tr *ngFor="let details of MyDigestEmailIdPrint"> <td> {{details.ContactName}}</td> <td> {{details.Email}}</td> <td> {{details.frequency}}</td> <td><input type="checkbox"></td> </tr> </tbody>
报错原因
- 核心问题是赋值逻辑错误:接口本身直接返回符合
*ngFor遍历要求的对象数组,但回调中用this.MyDigestEmailIdPrint.push(res)的写法,是把整个返回的数组作为单个元素塞进初始为空的数组,最终绑定的变量变成了二维数组[ [/* 接口返回的全量数据 */] ]。 *ngFor遍历第一层时拿到的是整个内部数组对象,不是单条联系人数据,Angular无法对非可迭代的普通对象做变更diff检测,就抛出了类型不支持的错误。- 附带逻辑漏洞:接口正常返回数组时不存在
res.message字段,res.message != "No Record Found"的判断永远成立,会错误执行push逻辑。
修复方法
直接修改TS文件中subscribe回调内的赋值逻辑,不要用push,改为直接赋值,同时补全类型判断兼容异常场景:
public MyDigestEmailIdPrint = []; DigestEmailIdPrint() { const postData = { clientid: localStorage.getItem("storageselectedclient"), }; this.article.DigestEmailIdPrint(postData).subscribe( (res) => { // 先校验返回值是否为数组,兼容无数据场景 if (Array.isArray(res)) { this.MyDigestEmailIdPrint = res; } else { // 无匹配数据时清空数组,避免残留旧数据 this.MyDigestEmailIdPrint = []; } }, (err) => { console.log(err); } ); }
可选优化
可以在模板里补充空状态提示,数据为空时表格不会显示空白:
<tbody> <tr *ngFor="let details of MyDigestEmailIdPrint"> <td> {{details.ContactName}}</td> <td> {{details.Email}}</td> <td> {{details.frequency}}</td> <td><input type="checkbox"></td> </tr> <tr *ngIf="MyDigestEmailIdPrint.length === 0"> <td colspan="4">暂无匹配的邮箱配置数据</td> </tr> </tbody>
内容的提问来源于stack exchange,提问作者kate moss
相关产品推荐
相关产品推荐

