如何正确使用AngularFire的OrderByDirection类型?
AngularFire排序问题解决:OrderByDirection报错与正确用法
错误原因
OrderByDirection是TypeScript的类型定义,仅用于做类型注解校验,不能当作具体的值来赋值或传入函数参数。你直接把它当作值使用,就会触发'OrderByDirection' only refers to a type, but is being used as a value here的报错。
正确用法说明
你之前觉得“不规范”的messQueryCheating其实是完全合规的写法——AngularFire的Firestore模块本身就是基于官方Firebase SDK封装的,它的query()方法原生支持接收Firebase SDK提供的查询操作符(包括orderBy),不存在“混用不规范”的问题。
修正后的示例代码
import { addDoc, collection, collectionData, doc, Firestore, query, updateDoc, OrderByDirection } from '@angular/fire/firestore'; import { orderBy } from "firebase/firestore"; getFireStoreCollection(id: any) { // 用OrderByDirection做类型校验,确保排序方向合法(只能是'asc'或'desc') const sortDirection: OrderByDirection = 'desc'; const messageCollection = collection(this.firestore, `tasks/${id}`); // 正确构建带排序的查询 const messQuery = query(messageCollection, orderBy("time", sortDirection)); const collectionSub = collectionData(messQuery, { idField: 'id' }) as Observable<Messages[]>; this.messagesSub = collectionSub.subscribe((mess) => { this.messages.next(mess); }); return this.messages.asObservable(); }
关键要点
OrderByDirection的作用是类型约束:确保你传入的排序方向是合法的(仅允许'asc'或'desc'),避免拼写错误;- AngularFire与Firebase SDK的查询操作符可以直接配合使用,这是官方设计的预期用法,无需顾虑;
- 动态切换排序方向时,用
OrderByDirection注解变量能在编译阶段就排查非法值问题。
内容的提问来源于stack exchange,提问作者Thomas Degroot
相关产品推荐
相关产品推荐

