AngularFire Rxjs subscription - return nill result

2019-08-21 02:00发布

I have two collections which I need to loop through, I start by geting the users groups, I then loop through each group and get the jobs associated with that group. This works perfectly, but the problem is that if there is no jobs the app stays in a loading state.

Here is my code:

this.fb
  .getUsersGroupsAsObservable(user.uid, groupType) // first get the users groups
  .subscribe(groups => {
    combineLatest( // for each group get the jobs belonging to that group
      groups.map(group => this.fb.getJobsbyGroup(group.id)),
    ).subscribe(res => { // if there is no results this wont execute
      this.jobs = [].concat.apply([], res);
    });
  });

Ideally it would be good if I could determine that the getJobsbyGroup is not returning any results and return an empty array. Sorry if this isnt worded well I'm not totally confident on the terminology needed in this case.

1条回答
姐就是有狂的资本
2楼-- · 2019-08-21 02:33

Can you check whether this is what you are looking for? link. This is the gist. you can check whether this.fb.getJobsbyGroup has result, then return result else return undefined.

  this.fb.getUsersGroupsAsObservable(user.uid, groupType)
.pipe(map(groups => groups.map(group => group.id)),
switchMap(groupIds => from(groupIds).pipe(mergeMap(id => this.fb.getJobsbyGroup(id).pipe(map(jobs => jobs ? jobs : []))),toArray())))
.subscribe()

Code Explanation: From the groups, isolate the groupIds into separate array. Then concurrently call getJobsbyGroup and check whether the result is there or return empty array. Then merge their results into a separate array and return it. Let me know whether this what you needed.

查看更多
登录 后发表回答