Go through a collection of Observables and store the outcome of each Observable in an array

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?

Answer №1

If you're looking for a solution, I recommend using the combineLatest method from RxJs library. You can find more information about it by visiting this link.

Here is a sample of how to use it in your code:

combineLatest(ARRAY_OF_OBSERVABLES)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((ARRAY_OF_RESPONSES) => {
    // Perform operations with ARRAY_OF_RESPONSES
})

In this context, ARRAY_OF_OBSERVABLES refers to an array of observables or requests, while ARRAY_OF_RESPONSES represents an array containing responses from those observables or requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an Angular 2 component that utilizes an interface within the constructor

If you have an interface named IData, and you want to develop an Angular 2 component that can accept any Class utilizing IData in its constructor, could this concept be implemented or is it off track? Your insights are greatly appreciated. ...

When any part of the page is clicked, the data on the Angular page will automatically

Clicking the mouse anywhere on the page, even in a blank spot, causes the data array to resort itself. I understand that clicking may trigger a view change if an impure pipe is set, but I have not used one. So I am puzzled because my development testing ...

Changing the color of the bullet icon in Angular material stepper based on a condition

Currently, I am working with the vertical stepper component from Material Angular. I am wondering how I can change the color of each icon based on a specific condition. If you want to take a look at my code, here is the StackBlitz link. Here is an exampl ...

MUI Chips serving as selectible tags with checkbox-like functionality

I have retrieved data from a JSON file containing information about different types of chips: [ { "id": "4", "name": "Caucasian" }, { "id": "5", "name": "Asian" }, ...

TSLint flagging a parsing issue in type guard while TypeScript compiler fails to pick up on any errors

I am facing an issue with my TypeScript method that includes a type guard: export function isArray(item: any): item is Array<any> { return item.constructor === Array; } After running tslint on the file, I encountered the following error message ...

Is there a way for me to access and install the Angular 2 release candidate through either npm or

When attempting to download Angular2 from npm or jspm, I am encountering an issue. Instead of getting the version 2.0.0-rc.1, I am receiving angular@^2.0.0-beta.17. Could this discrepancy be related to changes in the release candidate or it is a matter of ...

What is the best method to locate an element<T> within an Array[T] when <T> is an enum?

I've recently started learning TypeScript and exploring its functionalities. I could use some assistance in deepening my understanding. Within our angular2 application, we have defined an enum for privileges as follows: export enum UserPrivileges{ ...

Having trouble getting two separate static directories (Angular apps in the "dist" folder) to work in a Node.js Express framework setup?

I have encountered an issue with setting up my two Angular apps and a single Node app. Both Angular apps consume APIs from the Node app, and I am trying to configure these client apps using NodeJs. Although I wrote the following code, it is not functioning ...

Disabling behavior subjects in Angular 8: A guide to unsubscribing

Hello, I am currently working on an Angular8 application where I am utilizing Replay Subject and Behavior Subject. I have noticed that when initially clicking, the API is only hit once. However, if I switch between tabs, the subscription triggers multiple ...

What is the best way to establish communication between the browser and an express.js server while utilizing angular ssr?

I've encountered a server-side rendering (SSR) issue that does not seem to be addressed in either the Angular documentation or the new Angular developer documentation. My inquiry pertains to transferring data from the browser to the server, as oppose ...

Tips for utilizing RouterLink within an HTML template

Angular 2.3.0 I created a module in Angular 2 as shown below: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; impo ...

Angular's custom validator consistently returns a null value

I need help with validating the uniqueness of a username field in a form where an administrator can create a new user. I have implemented a uniqueUserNameValidator function for this purpose, but it always returns null. I suspect that the issue lies in the ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

What is the best way to modify the class of specific items within an ngFor loop in

I apologize if this question has already been addressed, but I couldn't find a suitable solution. My goal is to develop a basic chat application where messages sent by the current user are displayed on the right side of the screen, while messages from ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

What is the best way to incorporate Ekko Lightbox into an Angular 7 Project?

I'm facing an issue while implementing Ekko lightbox in my angular project. Specifically, I want to use it in a certain component but I am unsure about how to import the necessary files into that component. After installing Ekko via NPM, I found all ...

The HttpInterceptor is programmed to identify and capture 401 error responses

After successfully implementing a code that called a logout() method upon receiving a 401 response from the server, I encountered issues following an upgrade of Angular from 5.2 to 7.0.3. It seems like either the HttpInterceptor interface has been modified ...

Encountering a 403 error when attempting to upload files from Angular to a Micron

I have encountered an issue while attempting to upload multiple files to the Micronaut Rest API. The uploading process works seamlessly with Postman and Swagger in the Micronaut Rest API, but when using the Angular app, the POST method throws a 403 HTTP er ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...