Exploring Angular Ngrx: Implementing various API calls in a loop for an array

Here is the challenge: I need to extract information from an action payload that includes specific data structure. The payload looks like this:

 {
     firms: [{ id: 1, firmName: 'string', roles: ['admin', 'supadmin', 'user'] }],
     type: "loadFolder",
     userId: 1
 };

My task involves iterating through the roles array and making an httpCall for each role, passing in the userId as a parameter. After retrieving the data, I have to categorize it into three separate lists based on the roles (userList, adminList, supadminList). However, I'm currently stuck and unable to find a suitable solution.

loadFolder$ = createEffect(() => {
  return this.action$.pipe(
  ofType(SidebarAction.loadFirmSuccess),
  switchMap(action => {

    let roles: Array < string > = [];
    let supadminlist = [];
    let adminList = [];
    let userList = [];

    action.firms.map(
      firm => {
        firm.roles.map((role: string) => {
          roles.push(role);
        });
      }
    );
    
    roles.forEach(role => {
      this.sidebarService.getFolders(action.userId, role).subscribe(res => {
          switch (role) {
            case ('supadmin'):
              supadminlist = res;
              break;
            case ('admin'):
              adminList = res;
              break;
            case ('user'):
              userList = res;
          }
        });
    });

    return sidebarAction.loadFoldersSuccess({supadmin, adminList, userList});
      
  }),
);
});

I've attempted this approach, but I'm struggling with the implementation and unfortunately, this solution is not yielding the desired results.

Answer №1

Prioritize the completion of http-calls before triggering the loadFoldersSuccess action. Implement forkJoin to handle the async calls and then dispatch the loadFoldersSuccess action.

const folderData = {}
roles.forEach(role => {
  folderData[role] = this.sidebarService.getFolders(action.userId, role)
});

return forkJoin(folderData).pipe(map(response => {
    return sidebarAction.loadFoldersSuccess(response);
}));

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

What could be causing my if statement to fail even though the condition is met?

I'm attempting to generate dynamic fields based on my chosen attributes. I have two array objects called addAttributes and fakeAttributes. The fakeAttributes contain the details of the selected attributes. I have a dropdown select component that displ ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

When I click the submit button in Angular, I aim to generate an id without relying on any backend processes

Is it possible to generate a unique ID every time the submit button is clicked, without relying on any back end code in Angular? Here's my form: <form> <ion-grid> <ion-button size="large" type="submit"(click)="login()" expa ...

Looking to showcase a .tif image in your Angular project?

This code is functioning properly for .png images. getNextImage(imageObj:{imageName:string,cityImageId:number,imgNumber:number}):void{ this.imgNumber= imageObj.imgNumber; this.imagePath=`assets/images/${imageObj.imageName}.png`; this.cityIma ...

Issues with implementing routing children in Angular 8

Currently, I am in the process of building a website and facing some issues with implementing the admin section. Within my admin module, I have various components such as login, dashboard, products, etc. However, I am encountering an issue where the childr ...

Utilizing ES6 Promises in Mongoose with Typescript to Create a Seamless Chain

When attempting to chain ES6 promises with Mongoose 4.5.4, I encountered an error in Typescript. public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { ...

Individual static item within Material Table's DataSource

Can a single static object be passed instead of a list of User information in Material Table DataSource? User object with data - {idUser:1, lastName: "xyz", firstName: "abc" } Where idUser is obtained from a URL parameter. And displayed using the Materi ...

No error was flagged when the function had the potential to return undefined

getStage may sometimes return undefined without reporting any errors, which could potentially lead to a code crash. const a = Math.random() > 0.4 function getStage(): string { if(a) { return '' } } c ...

What is the best way to determine if a value from my array is present within a different object?

I have an array with oid and name data that I need to compare against an object to see if the oid value exists within it. Here is the array: const values = [ { "oid": "nbfwm6zz3d3s00", "name": "" ...

Iterating through an object using the forEach method (uncommon practice)

Greetings, I have the following object: data = { name: undefined, age: undefined, gender: undefined }; I am looking to iterate through each key and value pair in this object and perform an action. Here is my attempt: this.data.forEach((item: ...

Using the `forwardRef` type in TypeScript with JSX dot notation

Currently, I am exploring the different types for Dot Notation components using forwardRef. I came across an example that showcases how dot notation is used without forwardRef: https://codesandbox.io/s/stpkm This example perfectly captures what I want to ...

Nested REST API calls in Angular are causing only the inner call to be returned

When retrieving a ShoppingCart with ShoppingCartItems through an outer REST call, an Observable of the ShoppingCartItems is then used to make an inner call in order to enhance the items with a Provider. After the inner call, a tap(console.log) shows that ...

Tips for successfully sending properties from a parent component to a child component in a TypeScript and React application

I am trying to achieve prop passing from a parent component to a child component in React using TypeScript. However, I am unsure how to properly define these props in the type. Below is the code snippet: function Parent() { ...

How to effectively handle multiple conditional statements in TypeScript?

I attempted to implement a "multiple filter" feature in TS, so... If I don't provide any input -> all products are returned as usual; However, if I specify some parameters -> only products matching the parameters are returned. (I us ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

Developing an angular 6 web client for GRPC

Having experience with grpc using a .net client and a Java grpc server, how can I integrate a grpc web client on Angular 6 using TypeScript? Additionally, what is the process for creating proto files and their typings for TypeScript? I have been referenci ...

retrieve the checkbox formgroup using the Response API

After following a tutorial on creating dynamic checkboxes, I now need to implement dynamic checkboxes using an API request. In my implementation so far, I have defined the structure as shown below: inquiry-response.ts interface Item { // Item interface ...

When working with Typescript, it's important to handle errors properly. One common error you might encounter is: Error:(54, 33) TS2686: 'fabric' refers to a UMD global, but the current file is a module

Encountering an Issue: import {Canvas} from "fabric"; Error:(54, 33) TS2686:'fabric' refers to a UMD global, but the current file is a module. Consider adding an import instead. In my Angular project with TypeScript, I am using fabric which ...

Ways to refresh Prism.js upon ngModel update in Angular 5

Currently, I am in the process of developing a CMS and facing an issue with re-rendering Prism.js to display syntax highlighting in the preview whenever there is a change in the body of the article. Below is the template code: <textarea [(ngModel ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...