3

I've been trying to subscribe to a particular observable(i am a beginner to rxjs), but I keep failing. here is my code


here I need to assign the first element of usergroups array element to this.currentGroup

const selectedUserGroups$ =
this.userGroupsService.getUserGroupsWithUsers(this.selectedUserGroupIds).pipe(shareReplay());

this.selectedUserGroups$.subscribe( (usergroups: UserGroup[]) =>
this.currentGroup = usergroups[0]); 

if(this.currentGroup.users?.length >0) 
{
  this.showUsersList(); 
}

but this won't work as i expected, Appreciate your help regarding this

Thili
  • 748
  • 1
  • 9
  • 21
  • Your edition is pretty much a separate question, but: the `if(this.currentGroup.users?.length >0)` chunk should be under the `subscribe`, after the `this.currentGroup =` assignment, otherwise it'll run too early. And for further reading, here's an evergreen SO classic: https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – mbojko Oct 02 '21 at 20:23

1 Answers1

3
const selectedUserGroups$ = // assignment here
this.selectedUserGroups$.subscribe( //...

Those are two different objects: the variable in the function scope selectedUserGroups$ and the object property this.selectedUserGroups$.

Remove this. from the second line, for example. Or replace const selectedUserGroups$ = with this.selectedUserGroups$ =.

mbojko
  • 13,503
  • 1
  • 16
  • 26
  • Thanks that solves my problem partially but unfortunately I do have another problem, it does not wait until this.currentGroup get values. As per my understanding, it's not working the asynchronous way. it's executing lines below without waiting to assign values for this.currentGroup – Thili Oct 02 '21 at 05:09
  • FYI I have edited the posted code hereafter I changed this const selectedUserGroups$ to this.selectedUserGroups$ it's partially solved. asi saied above comment, now it's executing the if statement without waiting for this.currentGroup assigned it's values :-( – Thili Oct 02 '21 at 05:27