Splitting Ngrx actions for individual items into multiple actions

I'm currently attempting to create an Ngrx effect that can retrieve posts from several users instead of just one. I have successfully implemented an effect that loads posts from a single user, and now I want to split the LoadUsersPosts effect into individual LoadUserPosts effects for each user. How can I achieve this?

This is my current approach:

@Effect() loadUsersPosts$ = this.actions$
.ofType(LOAD_USERS_POSTS)
.mergeMap((action: LoadUsersPosts) => {
  const array = [];
  action.payload.forEach(user => {
    array.push(new LoadPosts(user));
  });
  return array;
});

Despite inserting console.log's within the forEach loop, it appears that the code isn't being executed at all.

Answer №1

It seems like the main goal you have is to transform and emit each value individually from an array in an observable stream. Instead of using a forEach loop, you can achieve this more efficiently by utilizing the map operator. By creating an observable from the transformed array with the help of the from operator, each value will be emitted sequentially. Here's a concise example:

Rx.Observable.of([1,2,3,4,5])
  .mergeMap(x => {
    const transformed = x.map(y => y * 2);
    return Rx.Observable.from(transformed);
  })
  .subscribe(x => { console.log(x); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.10/Rx.min.js"></script>

Answer №2

To achieve this functionality, you can use the following code snippet:

@Effect()
  loadUsersPosts$ = this.actions$
    .ofType(LOAD_USERS_POSTS)
    .pipe(
      switchMap((action: LoadUsersPosts) => from(action.payload)),
      map(user => new LoadPosts(user))
    );

The switchMap operator within this code will transform the outer observable into multiple inner observables based on the array provided in "action.payload" using the "from" Observable creator.

By using the "from" Observable creator, an observable stream is created from the array, emitting one value at a time.

The map operator then transforms these values into actions.

It's worth noting that switchMap is preferred over mergeMap in this scenario. While mergeMap provides output for all requests, switchMap cancels all but the latest request.

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

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...

What is the best way to convert canvas data into a string in Angular once the user has made a drawing on it?

I need help figuring out how to automatically store canvas data to a variable in Angular whenever the user draws or makes changes to it. Here is a snippet from my component.html file: <canvas id="canvas"></canvas> And here is part o ...

Refreshing a page while preserving the same URL

Looking for a way to reload the page at the same URL in Angular, I came across a solution that seems to work: this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => { this.router.navigate(['Your actual ...

Angular, manipulating components through class references instead of creating or destroying them

I am exploring ways to move an angular component, and I understand that it can be achieved through construction and destruction. For example, you can refer to this link: https://stackblitz.com/edit/angular-t3rxb3?file=src%2Fapp%2Fapp.component.html Howeve ...

Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API. One of the messages I ...

Designing a Test Specification for the @Input feature in Angular 2

@Input() public set isRunning(value: boolean) { if (!value) { this.cancelTimeout(); this.isDelayedRunning = false; return; } if (this.currentTimeout) { return; } ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Is it acceptable to include a @types library as a regular dependency in the package.json file of a Typescript library?

Should the library also be compatible with Typescript projects? I am developing a Typescript library that utilizes node-fetch and @types/node-fetch, which will be shared through an internal NPM registry within the company. If I only include @types/node-f ...

Angular Custom Validator Error (Validation function must either return a Promise or an Observable)

I created a personalized validator for the phone field but I'm encountering an issue The validator should be returning either a Promise or an Observable. Basically, I just want to check if the phone number is less than 10 characters. HTML Cod ...

When utilizing Next.js with TypeScript, you may encounter an error message stating that the property 'className' is not found on the type 'IntrinsicAttributes & IntrinsicClassAttributes'

I recently put together a basic nextjs app using typescript. Here's the link to the example: https://github.com/zeit/next.js/tree/master/examples/with-typescript However, I encountered an issue where I am unable to add the className attribute to any ...

Issue encountered while attempting to compare '[object Object]'. This operation is restricted to arrays and iterables

I'm puzzled by this error that keeps popping up in my code. The issue seems to be occurring in AppComponent.html:4. An error is appearing related to '[object Object]'. It seems that only arrays and iterables are allowed. app.component.ht ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Angular - Mark all checkboxes on/off

My task involves implementing a specific functionality. I have three checkboxes, and when one is selected, I want the other two to be automatically selected as well. I am using a pre-built component to create these checkboxes. <form [formGroup]="d ...

Searching in TypeScript tables with Angular's search bar

I've successfully completed a basic CRUD application, but now I need to incorporate a Search Bar that can filter my table and display rows with matching letters. I'm unsure how to approach this in my component. I've seen examples using pipe ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...

Execute an Asynchronous Operation in NgRx After Triggering an Action

Please note that this is a question seeking clarification Instructions Needed I am currently working on dispatching an action to NgRx in order to add a task to a list of tasks. Additionally, I need to perform a put request to an API to save the changes ma ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Angular2's asynchronous data binding is still lagging even after the data has been successfully loaded

I have integrated Firebase with Angular2 to retrieve an object. import { Component, OnInit } from '@angular/core'; import { AngularFire, FirebaseObjectObservable } from 'angularfire2'; import { ActivatedRoute, Params } from '@angu ...