Leveraging NgRx effects with mergeMap

I have developed two different approaches to achieve the same effect, and surprisingly both are functioning correctly. However, I am struggling to comprehend the nuances between them and determine which one is more "correct".

See them outlined below:

Option 1. The IDE is unable to infer the type for instance in the final map.

    pollingStarted$ = createEffect(() =>
        this.actions$.pipe(
            ofType(pollingStarted),
            mergeMap(action => action.instances),
            map(instance => performRequest({ instance }))
        )
    );

Option 2. All types are properly defined and clear. I personally consider this to be the more accurate approach, but I am eager to uncover and comprehend the distinctions.

   pollingStarted$ = createEffect(() =>
        this.actions$.pipe(
            ofType(pollingStarted),
            mergeMap(({ instances }) =>
                instances.map(instance => performRequest({ instance }))
            )
        )
    );

Answer №1

If you're looking for guidance on good and bad practices in Angular, check out this informative article.

Let's consider a scenario where you want to add another map within your second map.

   When working with nested maps, like in the example below, the code can quickly become unreadable and difficult to manage.
 

Handling errors can also become a challenge when dealing with multiple levels of maps.

Using the pipe operator is recommended for cleaner and more readable code, especially when dealing with nested operators like maps.

Refactoring code to simplify and improve manageability is crucial, as demonstrated by a recent experience in a large project.

Answer №2

It appears that the initial method may not be effective:

pollingStarted$ = createEffect(() =>
    this.actions$.pipe(
        ofType(pollingStarted),
        mergeMap(action => action.instances),
        map(instance => performRequest({ instance }))
    )
);

mergeMap in this scenario flattens your array, and map produces an Observable for each value emitted. Consequently, you end up with an Observable of Observables (

Observable<Observable<your type>>
). To resolve this, you should employ one of the Higher Order Observables instead of map.

The alternative approach is the correct one:

pollingStarted$ = createEffect(() =>
    this.actions$.pipe(
        ofType(pollingStarted),
        mergeMap(({ instances }) =>
           instances.map(instance => performRequest({ instance }))
        )
     )
 );

In this case, mergeMap combines an array of observables generated by instances.map into a single observable. Using this method allows you to have control over the observables, enabling you to apply catchError to each performRequest individually or implement it at a higher level after mergeMap for a unified error handling mechanism for all performRequest calls.

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

Issues arise when attempting to read data from a JSON file upon refreshing the Angular page

Currently, I am working on an Angular application where the client has requested to have the path of the backend stored in a JSON file. This will allow them to easily modify the path without requiring another deployment. I have implemented this feature su ...

Angular 2 release candidate 3 encounters issues with unfulfilled dependencies

Having encountered an issue with npm, specifically related to dependencies while using packages.json from the official Angular2 site's quick start guide. Yesterday everything was functioning correctly, but today I am facing difficulties as npm is unab ...

npm encountered an issue when attempting to install a package from a local directory: EISDIR: illegal operation on a directory, read

While attempting to add my compiled TypeScript output as a local package using npm, this error appears: $ npm install --save ../app/out npm ERR! eisdir EISDIR: illegal operation on a directory, read npm ERR! eisdir This is most likely not a problem wit ...

Understanding NestJS Mixins and Their Distinction from Inheritance

After researching, I found that the Nestjs documentation does not include any information about mixins. Here is what I have gathered from my findings on Google and Stack Overflow: A mixin serves as a means of code sharing between classes within Nest. Esse ...

Refused to run script from inline content on the lightweight server due to security policy restrictions

I have been adhering to Angular's best practices in order to create a Progressive Web App (PWA). After building the production version (ng build --prod --aot), I am running it from the dist folder on localhost using npm run dev ("dev": "lite-server"). ...

Provide initial values to a custom TypeScript hook

As a new TypeScript user, I am trying to implement a hook called useForm to use in all forms. However, I am facing an issue with passing initial values using the code snippet below. Can someone help me troubleshoot this? interface IForm1 { name?: strin ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

Struggling with the testing of @Output functionality through Jasmine

I've encountered an issue while trying to test an @Output parameter in my Jasmine test for Angular 5. It seems that the button click isn't being registered, resulting in the event emitter not triggering. Here is a snippet of my component code: ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Setting values to variables within a component to enable universal access throughout the component in Angular 2

In my Angular 2 project, I have a function that retrieves data from a database using an API. I've created a function that stores the data successfully in a variable named "ReqData", which is of type "any". this._visitService.getchartData().subscrib ...

Issues with Angular 6 Feature Modules: Interceptor failing to execute

I am delving into feature modules for the first time and struggling to get an interceptor to trigger. Adapting to the feature model pattern is a learning curve, and I am seeking guidance in identifying any misinterpretations. The named interceptor is "Auth ...

The CORS policy has blocked access to 'http://localhost:8080/BeginSignup' from 'http://localhost:4200'

I'm having trouble with a CORS policy error when sending a fetch POST request to my Golang AppEngine API. Although I don't understand why this error is occurring. Below is the code I'm using: Below is the Angular code calling the API: priva ...

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

Error code -8 occurred while executing the yarn dev command, unable to identify the issue

I'm facing an issue with my development script that is structured like this: "scripts": { "dev": "./test.sh", }, Upon running the 'yarn dev' command, I encounter the following error message: Internal Error: ...

Show all the input validation errors in Angular 4

I'm currently in the process of developing my first Angular 4 application. I am working on testing form validation using a template-driven approach and have added some validators to my form. Now, I am looking for a way to display validation errors fo ...

Having trouble compiling my Angular 13 application due to numerous node_module errors

I am facing an issue with Visual Studio 2022 where I am seeing thousands of errors coming from the node_modules folder. It's puzzling because just an hour ago, the project was compiling without any problems in VS. While ng build works fine and serves ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

History will still store CanActive URL even if it returns false

Why does CanActive add the skipped path to history? I'm using the following guard: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { if (this.router.url === '/') { thi ...

Utilizing Angular's ngIf directive to output the result of a condition

In my project, there is a unique card-list element that has the capability to display either elements from the card component or the card-edit component based on the value of the wasEditClicked property in the card component. The structure of the card-lis ...

Is it possible to utilize the NX CLI for managing both Angular and React applications within the same Nx workspace?

When attempting to set up my workspace, I encountered some errors. To start, I created an Nx workspace by running: npx create-nx-workspace@latest myworkspace, and then chose Angular CLI as the option. Next, I generated an Angular app using the command: y ...