如何按添加顺序从Firebase Collection中检索项目(AngularFire 5)?



我需要用户按照添加到 Firebase 的顺序显示在我的UsersListComponent中。

目前,如果我添加新用户,他可能会出现在列表的中间,但我希望新用户出现在列表的末尾。

如何使用 AngularFire 5 实现它?

我的UsersServiceUsersListComponent

export class UsersService {
usersCollection: AngularFirestoreCollection<User>;
users: Observable<User[]>;
constructor(private firebase: AngularFirestore) {
this.usersCollection = firebase.collection('users');
this.users = this.usersCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as User;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
}
getUsers(): Observable<User[]> {
return this.users;
}

export class UsersListComponent implements OnInit {
users: User[];
constructor(private usersService: UsersService) { }
ngOnInit() {
this.usersService.getUsers().subscribe(users => {
this.users = users;
});

通常,您需要更改此方法并在那里添加排序,或者在 fire store 上使用 orderby 方法作为 https://firebase.google.com/docs/firestore/query-data/order-limit-data

this.usersService.getUsers().subscribe(users => {
this.users = users.sort((x,y) => x.? - y.?);
});

但这还不够,您需要在存储到Firestore时为数据添加日期,然后按该日期排序

最新更新