Tips for asynchronously subscribing to an observable from an array in Angular

I am facing a scenario where I have an array containing IDs and I need to subscribe to observables for each ID in a sequential order. I attempted to use a foreach loop but the responses were not in the desired order. Then, I tried to implement a for loop and increment the index from the subscriber, but this caused the browser to crash due to a large number of requests being sent before the index changed.

Here is the code snippet I was working with:

const uniqueGroups=[1,2,3,4,5,6];
uniqueGroups.forEach(groupId => {
    this.magB1BaseService.getAttributeGroup(groupId)
      .subscribe(data => {
        this.AttributeGroups.push(data);
          this.AttributeGroupsCollapses[data.ID] = false;
        });
    });

Answer №1

To achieve this functionality, you can use the following approach:

    const distinctGroups = of(7, 8, 9, 10, 11, 12);
    
    distinctGroups.pipe(concatMap(groupID => (
      this.service.getGroupAttributes(groupID))
      .subscribe(response => {
        this.groupsList.push(response);
        this.groupCollapses[response.ID] = false;
      })));

Answer №2

Follow this code snippet to subscribe sequentially using the concat operator.

const uniqueItems = [7,8,9,10,11,12];
let subscribers: Array<Observable<any>> = [];
uniqueItems.forEach( itemId => {
   subscribers.push(this.customService.getItemDetails(itemId));
});
concat(...subscribers).subscribe( response => {
   this.ItemsList.push(response);
   this.ItemCollapses[response.ID] = true;
});

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

Cannot assign Angular 4 RequestOptions object to post method parameter

I'm having trouble with these codes. Initially, I created a header using the code block below: headers.append("Authorization", btoa(username + ":" + password)); var requestOptions = new RequestOptions({ headers: headers }); However, when I tried to ...

Creating Concurrent Svelte Applications with Local State Management

Note: Self-answer provided. There are three primary methods in Svelte for passing data between components: 1. Utilizing Props This involves passing data from a parent component to a child component. Data transfer is one-way only. Data can only be passed ...

Storing data from a popover form in ng-bootstrap for Angular 2+

Is there a way to include an input field in a popover and retain the entered values? When I click the popover button and enter text into the input field, the text disappears when the popover is closed If this is not achievable with ng-bootstrap, could it ...

Issues with redirecting to HTTPS on the homepage in Node.js and Express causing problems

I have set up two servers - one for http and the other for https on my VPS using Express: var httpServer = http.createServer(app); httpServer.listen(httpPort); var httpsServer = https.createServer(credentials, app); httpsServer.listen(httpsPort); To red ...

An error was encountered at line 7800, character 18 in the three-core.d.ts file in the node_modules/@types/three directory. The error message reads: "Cannot find name 'VRDisplay

I encountered an error in my Angular 6 app while running ng serve ERROR in node_modules/@types/three/three-core.d.ts(7800,18): error TS2304: Cannot find name 'VRDisplay'. node_modules/@types/three/three-core.d.ts(7801,23): error TS2304: Canno ...

The requested module cannot be located, were you referring to "js" instead?

I am currently developing a React application using webpack and typescript. I have integrated the dependency react-financial-charts into my project, and it is properly specified in the package.json. Inside the node_modules directory, there are two folders ...

Type inference and the extends clause in TypeScript 4.6 for conditional types

My focus was on TypeScript 4.7 when I created the following types: const routes = { foo: '/foo/:paramFoo', bar: '/bar/:paramFoo/:paramBar', baz: '/baz/baz2/:paramFoo/:paramBar', } as const; type Routes = typeof routes; ...

The return type from the RxJS Observable reduce method may differ from the type initially provided

Dealing with Angular4, TypeScript, and RxJS 5 I am encountering an issue where I have a complex type being passed into a reduce method, but I want the return type to be a simple boolean value. Currently, the following code is giving me a return type erro ...

The edited input is not being shown on the console when using the PUT method

I retrieved the data for the input fields (title and body) from this specific source (https://jsonplaceholder.typicode.com/posts). My goal now is to modify the text in either the title or body, so that when I use console.log(), it will show the updated tit ...

In Angular and Jasmine, it is important to note that when multiple actions are included within an it() function, they

I'm currently working on a test to ensure that each INPUT field is not empty. I seem to be facing some challenges in writing this test, which could be due to my lack of experience or the limitations of Jasmine when it comes to handling multiple action ...

Once the submit button is clicked in Angular Dev Extreme, validation processes are triggered once more

Currently experiencing an issue on a page with textboxes and validations. After entering values into the textboxes and clicking submit, the values successfully pass to the database, but the validations continue to appear again upon submitting. This problem ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Utilize @ngrx/store to merge various reducers from feature modules

I'm currently immersed in developing a test app to delve deeper into the @ngrx/store framework. Within this project, I've set up a module called TrainingModule that aims to store various exercises and related information. The code is functioning ...

Expressions without a call signature cannot be invoked

When using an adapter in the given example, I encountered a type error specifically on the last line of the getGloryOfAnimal method. Despite having clearly defined types, I am puzzled by this issue. interface ICheetah { pace: string; } interface ILio ...

Unable to allocate information in the subscribe method

I'm experiencing an issue with the post method. Whenever I try to retrieve data using the segmentService, I always receive an empty segmentdata object in my temporarySegment variable. Strangely enough, when I use the same approach for retrieving numbe ...

ng-for loop not properly rendering array of collections in table cells

I've been working on developing a MEAN Stack application that deals with mongoDB data related to hostels. hostels { "_id" : ObjectId("5e3c21c03d8d54b35af796ed"), "Hostel" : "The traveler's Lodge", "Rooms" : 23, "Customer" : [ { ...

Problem: When trying to access the property 'completed' of an object in Angular 2, an error is

My understanding is that by using @Input(), this component should be able to bind <experiment [experiment]="experiment.completed"></experiment>. Here is the hierarchy: https://i.stack.imgur.com/6UwHt.png experiment.detail.component.ts import ...

Why is Angular.orderBy not displaying any data on the Page?

Embarking on my first Angular project with Firebase Firestore, I am excited to showcase some of the code below. I recently learned Angular and here is what I have accomplished so far: Component.html <section class="rank"> <p class=& ...

Animated CSS side panel

I'm currently working on creating an animation for a side menu. The animation works perfectly when I open the menu, but the problem arises when I try to animate it back closed. Is there a property that allows the animation to play in reverse when the ...

Tips for sorting through the properties of the Record<K, T>:

Let's say we have the following data stored in a record: export const MenuData: Record<Header, HeaderInfo> = { val1: { message: 'xyz', buttonText: 'txt', buttonUrl: '/url-abc', }, val2: { messa ...