尝试使用 angularfire 在 angular 中加入一对多的 firebase 文档
Trying to join one-to-many firebase documents in angular using angularfire
我知道之前有人问过这个问题,但我无法从提供的典型答案中找出我的情况。在我的应用程序中,我有一个名为 objectives 的 firebase 集合和一个具有一对多关系的任务集合。每个 objective 都有一个任务数组(填充了任务的 ID),每个任务都有一个 objectiveId。我想加入这些,所以当我调用 snapshotChanges() 来获取所有 objectives 时,我想 return 一个 objectives 的数组,其中嵌套了任务对象。
我有这段代码,我知道它不起作用,因为我不能 return observable 中的东西,但我想知道在这种情况下我将如何使用 RxJS 运算符?
loadObjectives() {
return this.objectivesCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(_ => {
const id = _.payload.doc.id;
const data = _.payload.doc.data();
const tasks = this.afs
.collection<Task>("tasks", ref =>
ref.where("objectiveId", "==", id)
)
.valueChanges().subscribe( tasks => {
return new Objective(id, data.title, tasks);
});
});
}),
tap(objectives => {
this._objectives.next(objectives);
})
);}
这可以通过一些巧妙的 RxJS 代码来完成,但通过在组件之间传递 props 通常更容易连接数据。例如,先阅读您的目标,然后将 ID 向下传递给 child 到 运行 另一个任务查询。
<objectives-list *ngFor="let obj of objectivesCollection | async">
<tasks-list [objective]="obj">
但为了回答您的问题,下面的代码将从目标开始,然后将每个结果映射到任务查询。最终结果将是一个数组数组(任务集合)。
this.objectivesCollection.valueChanges({idField: 'id'}).pipe(
switchMap(objectives => {
// map each objective to a task query
const joins = objectives.map(obj => this.afs
.collection<Task>("tasks", ref => ref.where("objectiveId", "==", obj.id))
.valueChanges()
)
// execute all queries concurrently with combineLatest.
return combineLatest(joins)
})
)
我知道之前有人问过这个问题,但我无法从提供的典型答案中找出我的情况。在我的应用程序中,我有一个名为 objectives 的 firebase 集合和一个具有一对多关系的任务集合。每个 objective 都有一个任务数组(填充了任务的 ID),每个任务都有一个 objectiveId。我想加入这些,所以当我调用 snapshotChanges() 来获取所有 objectives 时,我想 return 一个 objectives 的数组,其中嵌套了任务对象。
我有这段代码,我知道它不起作用,因为我不能 return observable 中的东西,但我想知道在这种情况下我将如何使用 RxJS 运算符?
loadObjectives() {
return this.objectivesCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(_ => {
const id = _.payload.doc.id;
const data = _.payload.doc.data();
const tasks = this.afs
.collection<Task>("tasks", ref =>
ref.where("objectiveId", "==", id)
)
.valueChanges().subscribe( tasks => {
return new Objective(id, data.title, tasks);
});
});
}),
tap(objectives => {
this._objectives.next(objectives);
})
);}
这可以通过一些巧妙的 RxJS 代码来完成,但通过在组件之间传递 props 通常更容易连接数据。例如,先阅读您的目标,然后将 ID 向下传递给 child 到 运行 另一个任务查询。
<objectives-list *ngFor="let obj of objectivesCollection | async">
<tasks-list [objective]="obj">
但为了回答您的问题,下面的代码将从目标开始,然后将每个结果映射到任务查询。最终结果将是一个数组数组(任务集合)。
this.objectivesCollection.valueChanges({idField: 'id'}).pipe(
switchMap(objectives => {
// map each objective to a task query
const joins = objectives.map(obj => this.afs
.collection<Task>("tasks", ref => ref.where("objectiveId", "==", obj.id))
.valueChanges()
)
// execute all queries concurrently with combineLatest.
return combineLatest(joins)
})
)