What are the limitations of using concatMap for handling multiple requests simultaneously?

In my current function, I am receiving an array of objects called data/ids as a parameter. Within this function, I need to execute a post request for each element/id:

fillProfile(users) {

    const requests = [];
    console.log( 'USERS.length:', users.length );
    requests.push( this.http.post( '/test/add', users[i] ) );

    for ( let i = 0; i < users.length; i++) {
        return this.http.post( '/test/add', users[i] ).pipe(
            map( (res) =>  {
                console.log( 'res: ', res );
                return res;
            }),
            catchError(err => {
                return throwError(err);
            })
        );
    }

Although my current implementation works, it is not considered a good practice. From my research so far, I have found that this can be achieved using forkJoin or other operators. I have attempted some solutions mentioned on Stack Overflow but none of them seem to work.

One approach I tried which was unsuccessful:

 ....
 return from(requests2).pipe(
     concatMap((request) => request.pipe(
         delay(500),
         map( res => {
             // console.log( 'res: ', res );
             return res;
         })
    ))
);

Do you have any suggestions on how to improve the execution of multiple requests, and also handle responses and errors of each one separately in a more efficient manner?

Answer №1

Rectified. My error stemmed from thinking in the wrong direction and also encountering a bug while creating an array. Here is how it functions now:

Within the service:

getArrayIds(users) {
    this.observables = [];
    for ( const i in users) {
        this.observables.push( this.http.post( '/test/add', users[i] ) );
    }
}


fillProfile(users): Observable<any> {
    return from(this.observables).pipe(
        concatMap((request) => request.pipe(
            delay(10),
            map( res => {
                return res;
            })
        ))
    );
}

Within *.component.ts:

....
public results$: BehaviorSubject<Array<any>> = new BehaviorSubject([]);

....
this.surveyService.answerSurveyQuestions(body).subscribe(res => {
     console.log( 'response: ', res );
     this.results$.next(this.results$.getValue().concat(res));
});

You can even display the results$ in the View and debug all the responses. Special thanks to this question and the helpful answers provided there!

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

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

Encountering a Next.js event type issue within an arrow function

After creating my handleChange() function to handle events from my input, I encountered an error that I'm unsure how to resolve. Shown below is a screenshot of the issue: https://i.sstatic.net/fWJA2.png I am currently working with Next.js. In React ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...

Angular 2 router hybrid application: URL resets after navigation

Each time a route is changed, the correct component is rendered but there seems to be an issue with the path. For example, when navigating from /items to /add-item, the URL changes momentarily but then reverts back. This issue occurs on every page, reg ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

Regular Expressions: Strategies for ensuring a secure password that meets specific criteria

Struggling to craft a regex for Angular Validators pattern on a password field with specific criteria: Minimum of 2 uppercase letters Minimum of 2 digits At least 1 special character. Currently able to validate each requirement individually (1 uppercase ...

The mysterious case of the missing currentUserObj in Angular with rxjs Subject

I've encountered an issue while trying to pass data from my login component to the user-profile component using an rxjs subject. Despite calling the sendUser method in the login component and subscribing to the observable in the user-profile component ...

Enhancing TypeScript builtin objects in Netbeans using a custom plugin

While in the process of converting JavaScript code to TypeScript, I encountered a challenge with extending built-in objects using Object.defineProperty, such as String.prototype. Object.defineProperty(String.prototype, 'testFunc', { value: funct ...

The module 'AppModule' raised an error due to an unexpected value being imported, specifically 'AngularFireDatabase'. For proper functionality, consider adding a @NgModule annotation

App.Module.ts import { AngularFireDatabase } from 'angularfire2/database'; imports: [ AngularFireDatabase ] I can't seem to figure out why it is requesting me to include a @NgModule annotation when I believe it is unnecessary. My ...

Steps for accessing a particular item with *ngfor in Angular 2

I'm struggling to figure out why both elements of my array are displaying simultaneously in my browser instead of separately. Take a look at this screenshot to see what I mean: https://i.stack.imgur.com/0EKSn.png Is there a method to specifically ac ...

What is the approach to merge an inner observable in RxJs with the outer observable and produce a single array as output

Whenever I execute the following code: timer(1000).pipe( expand(() => of('a')), take(3) ) .subscribe(data => alert(data)); I receive three alerts: one with 0, another with 'a', and a third one also with 'a'. I wo ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Ensure the variable is valid by using a type guard in the false branch

I am attempting to use a type guard to narrow down a complex type. In my scenario, I want the false branch of the type guard to recognize the complement of the narrowed type. interface Model { side: 'left' | 'right'; } interface LeftMo ...

Managing Multiple Operations in Angular Firestore

For the past few weeks, I've been grappling with the theory behind this issue. Despite scouring the internet for solutions, I haven't found anything truly helpful. So, I'm turning to the SO community for the first time. In my Firestore data ...

Angular 8 wild card redirect problem with Routable Modals

I have a Modal that can be routed with unique parameters to display Training content defined in the app-routing.module.ts file { path : 'TopshelfContent/:catName/:cmsID', component: ModalContainerComponent, canActivate: [MsalGuard]}, When manua ...

Structuring an Angular 2 Project

Embarking on a new project in Angular2, I find myself pondering the optimal structure for an Angular2 application. Imagine I have various pages such as home, auto-galleries, nearest-galleries, brands, cars, and selected-car. The navigation sequence could b ...

Tips for setting up the configuration of @typescript-eslint guidelines

I am in the process of transitioning to @typescript-eslint but I am finding the documentation to be quite inadequate. One specific issue I am facing is the errors like the following: Line 58: Expected a semicolon @typescript-eslint/member-del ...

What steps should I follow to implement Cypress in an older project?

Looking to automate a project built with Node.js version 8.9.4 and an older version of Angular using Cypress for testing, but running into compatibility issues with the current version of Cypress. Is there a way to use an older version of Cypress in this ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

Unable to access setRowData() in AgGrid/Angular 2 leads to rendering of the grid without displaying any rowData

Resolved I think my solution is temporarily fixed and it reveals that I may have set up my mongoose model incorrectly. The answer provided did assist me in solving my issue, but ultimately the reason for the empty data rows was due to incorrect identifier ...