Performing a series of HTTP requests within a single @ngrx/effect

I need some guidance as I am new to @ngrx and feeling a bit lost in understanding how it should be used.

Let's assume we have an effect named PlaceOrderEffect

In this effect, my goal is to handle each request in a specific order.

processOrder$ = createEffect(
   ofType(OrderActions.PROCESS_ORDER),
   //this part is where I'm struggling
   concatMap([
      this.service.addCrust(),
      this.service.addTopings(),
      this.service.sendToCook()
      this.service.checkOut()
   ]
)

How can I ensure that these operations run sequentially and manage the final response effectively?

Answer №1

concatMap is a useful RxJS operator when used with the pipe. It merges the source observable with a new one returned by concatMap, but in your specific case, it may not be necessary.

If your requests are independent of each other, you can achieve the desired outcome by using the RxJS concat function as shown below:

processOrder$ = createEffect(() =>
    this.actions$.pipe(
        ofType(OrderActions.PROCESS_ORDER),
        switchMap(({ payload }) =>
            concat(
                this.service.addCrust(),
                this.service.addToppings(),
                this.service.sendToCook(),
                this.service.checkOut()
            )
        )
    )
);

However, if each request depends on the previous one, you should use the concatMap operator like this:

processOrder$ = createEffect(() =>
    this.actions$.pipe(
        ofType(OrderActions.PROCESS_ORDER),
        concatMap(({ payload }) => this.service.addCrust(payload)),
        concatMap((response1) => this.service.addToppings(response1)),
        concatMap((response2) => this.service.sendToCook(response2)),
        concatMap((response3) => this.service.checkOut(response3))
    )
);

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

Hidden back navigation strategy in AngularJS 2 with location strategy

After creating a custom LocationStrategy to disable browser location bar changes, I am now looking to integrate smaller apps into various web pages without affecting the browser's location. While navigation works smoothly with this new strategy, I am ...

Initial request in the sequence is a conditional request

Currently, I am attempting to make a request in rxjs that is conditional based on whether or not the user has uploaded a file. If a file has been uploaded, I need to attach it to the user object before sending it off, and then proceed to patch the user aft ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Unable to establish a connection with ngModel despite the FormsModule module being successfully imported

I'm currently following the tutorial Tour of Heroes and I've reached a point where I need to add my first input field. Even though I have included FormsModule in AppModule, I keep getting an error saying "ng Can't bind to '{ngModel}&apo ...

Generating dynamic text in Angular based on certain conditions

I am still learning about Angular. Can someone please explain how to make text dynamic based on a count? For example, if the count is greater than 2, the text should be "Teams," and if it is less than or equal to 2, the text should be "Team." Here is what ...

The function cloneElement does not share any properties with the type Partial<P> and Attributes

I'm encountering a perplexing issue with my code. When I attempt to call cloneElement with the second parameter being of type Type { foo: number } has no properties in common with type 'Partial<Child> & Attributes', TypeScript thro ...

Angular 7 automatically updates array values with the most recent values, replacing any previous values in the process

Currently, I'm working with arrays and utilizing the map function to modify the data. Below is an array of icons: private socialIcons:any[] = [ {"icon":"thumbs-up","operation":"like"}, {"icon":"thumbs-down","operation":"unlike"}, {" ...

What is the process of transforming two forms into components and then integrating those components into a view in Angular 5?

Currently, I have two forms running smoothly on the same component as shown in InfoAndQualificationComponent.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from "@angular/forms"; @Component({ selector: ...

Collaborating on code between a Typescript React application and a Typescript Express application

Struggling to find a smart way to share code between two interconnected projects? Look no further! I've got a React web app encompassing client code and an Express app serving as both the API and the React web app host. Since I use Typescript in both ...

The e2e Protractor test is unable to identify the Angular component within a complex Angular router with multiple layers

I am currently working on an Angular application and I need to set up end-to-end testing for this project. Angular Package: 4.6.6 Protractor: 5.3.0 In addition, my project includes a multi-layer router that wraps the router-outlet into another component ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

The metadata version discrepancy has been detected for the module located at C:/xampp/htdocs//node_modules/angular2-flash-messages/module/index.d.ts

While working with Angular 4, I encountered an error after trying to install angular2-flash-messages using npm with the following command: npm install angular2-flash-messages --save The error I encountered can be viewed in the following image: enter im ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

Ways to determine the types of props received by a function when the arguments vary for each scenario?

I have a specialized component that handles the majority of tasks for a specific operation. This component needs to invoke the onSubmit function received through props, depending on the type of the calling component. Below is an example code snippet show ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

Encountering challenges while integrating Angular with a Laravel forum creation project

Currently, I am working on building a forum application that involves users, posts, and comments using Laravel. However, the next step in my project requires integrating Angular, which is new territory for me and I'm not sure where to start. I have a ...

Using a specific type of keys, attempting to set two instances of those keys simultaneously will result in an error of that type

Consider this scenario: type Example = { x: string, y: number } const a: Example = { x: "x", y: 1 } const b: Example = { x: "y", y: 2 } const issue = (keys: (keyof Example)[]) => { keys.forEach(key => { a[key] ...

What could be causing the undefined properties of my input variables in Angular?

Currently, I am fetching data from a service within the app component and passing it down to a child component using @Input. Oddly enough, when I log the data in ngOnInit, it appears correctly in the child component. However, when I try to assign it to a v ...

How to send variables to a function when a value changes in TypeScript and Angular

As someone who is new to Angular and HTML, I am seeking assistance with the following code snippet: <mat-form-field> <mat-select (valueChange)="changeStatus(list.name, card.name)"> <mat-option *ngFor="let i of lists"> {{i.name}} ...

Avoiding the use of destructuring for undefined values in JavaScript can be achieved by implementing

Upon receiving the response registryReportSettings from the server: this.getRegistrySettings(registry.Id).subscribe((registryReportSettings: { extended: ReportPropertiesRequest }) => { const { objectProperties, reportProperties, textProperties } = reg ...