AngularFire Firestore是否支持多个orderBy链式调用实现多条件排序
问题解答
AngularFire 完全支持多条件排序功能,你代码里链式调用orderBy的写法本身符合规范,报错和AngularFire的排序逻辑无关。
错误原因定位
从你提供的报错栈可以看出,错误触发点是Angular Material的MatTableDataSource组件内部逻辑:组件在处理数据时尝试读取数据的length属性,但此时拿到的数据是undefined,所以抛出类型错误。
触发undefined的场景在你的错误回调逻辑里:当请求失败时,你执行了this.baseballCardsChanged.next(undefined);,如果订阅这个事件的逻辑直接把返回值赋值给了MatTableDataSource的data属性,就会触发这个报错。
解决步骤
- 修正请求失败的返回值:将错误回调中的
this.baseballCardsChanged.next(undefined);改为返回空数组:
(err) => { this.uiService.loadingStateChanged.next(false); this.uiService.showSnackbar('Fetching Cards failed, please try again later', undefined, 3000); this.baseballCardsChanged.next([]); // 替换原来的undefined }
- 增加数据空值兜底:在请求成功拿到数据时也增加兜底逻辑,避免偶发的空数据问题:
(cards: any) => { this.uiService.loadingStateChanged.next(false); this.baseballCards = cards || []; // 增加空值兜底 this.baseballCardsChanged.next([...this.baseballCards]); }
- (可选)确认Firestore复合索引已创建:多字段排序需要提前在Firebase控制台创建对应的复合索引,如果后续出现索引缺失的报错,按照控制台提示创建即可。
内容的提问来源于stack exchange,提问作者Khepf
相关产品推荐
相关产品推荐

