I am trying to map an observable, get a value from my returned observable then feed this value into another observable and return that result. Here is what I have so far:
getJobsByUser(user: User): Observable<Job[]> {
return this.getUsersGroupsAsObservable(user.uid, 'contacts').map(groups => {
groups.map(group => {
this.getJobsbyGroup(group.id);
});
});
getJobsbyGroup(groupId: string): Observable<Job[]> {
return this.afs
.collection<Job>('jobs', ref => ref.where(`group.${groupId}`, '==', true))
.valueChanges();
}
getUsersGroupsAsObservable(
userId: string,
type: string = 'users',
): Observable<Group[]> {
return this.afs
.collection<Group>('groups', ref =>
ref.where(`${type}.${userId}`, '==', true),
)
.valueChanges();
}
The problem is typescript is indicating that my getJobsByUser function will return an observable of type:void. When I do output it on my template I get nothing or undefined. I feel like I need to use switchMap but im a little fuzzy with rx/js. I am unsure how to return an Observable of type Job[]
Update: With help from @Pranay Rana I am now returning array, and can get the first value like this:
getJobsByUser(user: User): Observable<Job[]> {
return this.getUsersGroupsAsObservable(user.uid, 'contacts').pipe(
mergeMap(groups => {
// returns an array of groups - we need to map this
return this.getJobsbyGroup(groups[0].id); // works with the first value - do we need another map here?
}),
);
}
Update 2: I have managed to get some data back from firestore, but it is emitting multiple observables rather than a combined stream:
this.fb.getUsersGroupsAsObservable(user.uid, 'contacts')
.switchMap(groups => {
return groups.map(group => this.fb.getJobsbyGroup(group.id));
})
.subscribe(res => {
console.log(res);
// this emits multiple observables rather than one
this.job$ = res;
});
return this.getJobsbyGroup(group.id);
– Ramesh RajendranflatMap
– Sachila Ranawaka