As a newcomer to Angular and RxJS, I am facing a challenge with handling social posts. For each post, I need to make a server call to retrieve the users who reacted to that post. The diagram linked below illustrates the process (the grey arrows represent requests): https://i.stack.imgur.com/JUBAh.png
I have developed a service that returns the users associated with a specific post. Here is the code snippet for this service:
The service function:
getUsersForSocialPost(socialPostId: number, count: number): Observable<any> {
return this.apollo
.query({
query: GET_USERS_CREATED_REACTION_ON_SOCIAL_POST,
variables: {
socialPostId,
take: count
}, fetchPolicy: 'network-only'
}).pipe(take(1), catchError(err => throwError({message: err.networkError.error.errors[0]})));
}
The component function:
for (const post of this.pagedSocialPosts) {
const id = post.id;
const viewCounter = post.reactionGists.find((item => item.type === 'VIEW')).count;
const socialPostStats = {socialPost: post.value, views: viewCounter, users: []};
/!* Make a call to retrieve all users from the database *!/
observables.push(this.socialPostService.getUsersForSocialPost(+id, +viewCounter)
.subscribe((result): any => {
const socialPostReactionGists: SocialPostReactionGist[] = result.data.socialPostById.reactionGists;
const users: User[] = [...socialPostReactionGists.find((item => item.type === 'VIEW')).PagedUsers.items];
if (users.length > 0) {
users.forEach((user) => socialPostStats.users.push(user.email));
}
socialPostsStats.push(socialPostStats);
}, error => {
this.toastService.error(
`${error.message.message}`,
'Can\'t fetch users:',
{disableTimeOut: true});
}));
}
console.log('Social Posts Stats: ', {location: this.location.displayName, socialPostsStats});
Since the code operates asynchronously, the console.log
statement prints an empty array. I have explored using the forkJoin
operator as suggested in other posts, but it requires additional iterations to create the final object. Are there alternative approaches or better solutions that can reduce the number of iterations needed?