我正在用Angular 6和angularfire2做一个Web应用程序。我正在获取集合中的所有文档,但是,现在我需要查询这些文档以获取具有字段role.moderator == true
的所有文档。
private usersCollection: AngularFirestoreCollection<User>;
users: Observable<UserId[]>;
moderators: Observable<UserId[]>;
constructor(
private afs: AngularFirestore
) {
this.usersCollection = afs.collection<User>(config.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};
}))
);
// Query this.users ?
}
用户界面为:
export interface User {
firstName: string;
lastName: string;
emailAddress: string;
roles: Roles;
officeAssignedId: string;
}
export interface UserId extends User {
id: string;
}
export interface Roles {
administrator?: boolean;
moderator?: boolean;
}
要让所有用户担任主持人,我正在做
getUsersWithModeratorRole() {
return this.afs.collection<User>(
config.collection_users,
ref => ref.where('roles.moderator', '==', true)).snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as User;
const id = a.payload.doc.id;
return {id, ...data};
}))
);
}
问题是:
this.users
),我只需要按字段查询即可。.take(1)
内做.toPromise()
和getUsersWithModeratorRole
方法,但是只返回一个用户,我需要全部。我以为有了.take(1)
就可以抢走一切。我的目标是查询我已经拥有(this.users
)的集合,以查找具有字段role.moderator == true
的所有用户,或将getUsersWithModeratorRole
方法正确转换为Promise以获取所有内容
答案 0 :(得分:0)
您可以创建一个在服务上返回Observable的方法,如下所示:
getUsersWithModeratorRole(): Observable<UserId[]> {
return this.users.pipe(
map(users => users.filter(user => user.roles.moderator === true))
);
}
或者,如果您希望它返回承诺,我想这将是这样的:
getUsersWithModeratorRole(): Promise<UserId[]> {
return this.users.pipe(
take(1),
map(users => users.filter(user => user.roles.moderator === true))
).toPromise();
}