我创建了一个Angular RecipeService,它使用angularfire2包装器查询Cloud Firestore数据库。该服务发出可观察到的食谱列表,然后由几个组件订阅。
它与硬编码的查询参数配合使用非常好,但是我一辈子都无法弄清楚如何更改查询参数以反映不同的过滤和排序选项。例如,用户可能想按日期与分数进行排序,或者只查看特定用户的食谱等。
恐怕答案是,一旦组件订阅了可观察对象,就无法更改查询参数。我还怕我会被告知,我必须在客户端执行必要的排序和筛选,而不是将工作分担给db。真的没有办法订阅数据库查询,然后操纵参数来更改结果集吗?
recipes.service.ts:
export interface Recipe {
id: string;
score: number;
title: string;
user: string;
timestamp: firebase.firestore.FieldValue;
}
export class RecipeService {
recipeCollection: AngularFirestoreCollection<Recipe>;
constructor(
private afs: AngularFirestore) {
this.recipeCollection = this.afs.collection('recipe',
ref => ref.orderBy('score','desc'));
}
getRecipes(): Observable<any[]> {
return this.recipeCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Recipe;
const id = a.payload.doc.id;
console.log( data.title );
return { id, ...data };
});
})
);
}
}
recipelist.component.ts:
export class RecipeListComponent implements OnInit {
public recipes: any;
constructor(private rs: RecipeService) { }
ngOnInit() {
//subscribe to recipeService
this.rs.getRecipes().subscribe(recipes => {
if (recipes) {
this.recipes = recipes;
} else {
this.recipes = null;
}
});
}
}
recipelist.component.html:
<app-recipe *ngFor="let recipe of recipes" [recipe]="recipe"></app-recipe>
我正在使用Angular 6和AngularFire 5.0.0-rc.11。