You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5报错:TypeError: 无法读取undefined的toLowerCase属性

解决FireStore数据表格过滤时的字段错误问题

看起来你在过滤FireStore数据表格的时候碰到了头疼的错误,虽然你说每个文档都明确定义了auteur字段,但大概率是数据流处理或者过滤逻辑里的小疏漏导致的,我来给你梳理几个排查和解决的方向:

1. 先确认FireStore数据是否正确映射到组件

如果你用的是snapshotChanges()获取数据,它返回的是包含元数据的快照对象,不是直接的文档数据。你需要先提取出data()部分,否则直接访问auteur会找不到字段:

// 错误示例:直接使用快照对象
this.items$ = this.firestore.collection('你的集合名').snapshotChanges();

// 正确方式:映射出文档数据
this.items$ = this.firestore.collection('你的集合名').snapshotChanges().pipe(
  map(actions => actions.map(action => {
    // 提取文档数据,并加上id
    const docData = action.payload.doc.data() as { auteur: string };
    const id = action.payload.doc.id;
    return { id, ...docData };
  }))
);

建议定义一个TypeScript接口来约束数据类型,这样编译时就能提前发现问题:

interface DocumentData {
  auteur: string;
  // 其他字段按需添加
}

2. 过滤逻辑要处理undefined的情况

即使文档里有auteur字段,也可能因为异步加载的时序问题,在过滤时数据还没完全就绪,导致访问item.auteur时出现undefined错误。可以用可选链操作符?.来避免:

// 错误示例:直接访问auteur,未处理undefined
filteredData = this.items.filter(item => item.auteur.includes(this.searchTerm));

// 修正后:先判断auteur存在再执行过滤
filteredData = this.items.filter(item => item?.auteur?.includes(this.searchTerm));

3. 确保过滤时机在数据加载完成后

如果是手动订阅数据,不要在ngOnInit里直接执行过滤,要等到数据返回后再处理:

ngOnInit() {
  this.dataService.getYourData().subscribe(items => {
    this.items = items;
    // 数据赋值完成后再执行过滤
    this.applyFilter(this.currentSearchTerm);
  });
}

applyFilter(searchTerm: string) {
  this.filteredData = this.items.filter(item => item?.auteur?.includes(searchTerm));
}

如果用的是Angular的async管道,确保模板里的数据是已经解析完成的:

<table [dataSource]="items$ | async">
  <!-- 表格列定义 -->
  <ng-container matColumnDef="auteur">
    <th mat-header-cell *matHeaderCellDef>作者</th>
    <td mat-cell *matCellDef="let item">{{ item.auteur }}</td>
  </ng-container>
</table>

4. 排查数据服务中的逻辑

检查你的DataService里获取FireStore数据的代码,是否有遗漏的映射或者错误的集合路径,确保返回的Observable确实包含正确的auteur字段。

内容的提问来源于stack exchange,提问作者RxDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:06:28