Tips for ensuring that the code inside a subscribe block completes before moving on to the next iteration within a forEach loop in Angular

Within the code snippet below, there exists a for loop where an API call is made. The intention is to have the 1st API call complete and execute all the subscribed code before moving on to the next iteration of the loop, triggering another API call.

Currently, the APIs are running concurrently rather than sequentially as desired.

                      parentLevelIdArray.forEach(parentLevelId => {
                        this.locModService.deleteAPI(parentLevelId, levelObj.id)
                        .subscribe((response) => {
                          if (response.status === 200) {
                            this.message = 'Image uploaded successfully';
                            this.getSublevels();
                            this.getAllLinkedLevel();
                          } else {
                            this.message = 'Image not uploaded successfully';
                          }
                        }
                        )
                      });

Despite searching through various stackoverflow threads, I have yet to find a suitable solution tailored to my specific scenario. Any assistance would be greatly appreciated.

Answer №1

To achieve this, I recommend converting it into an array of observables:

const tasks = parentLevelIdArray.map((parentLevelId) => this.locModService.deleteAPI(parentLevelId, levelObj.id))

By doing this, you can then use the concat method to execute them sequentially as required:

concat(tasks).subscribe((response) => {
  if (response.status === 200) {
    this.message = 'Image uploaded successfully';
    this.getSublevels();
    this.getAllLinkedLevel();
  } else {
    this.message = 'Image not uploaded successfully';
  }
}

Answer №2

I have come up with a solution using recursion.

Original method --

let lastIndex = parentLevelIdArray.length - 1;
this.recursiveDelete(parentLevelIdArray, levelObj, lastIndex);

Method being called --

recursiveDelete(parentLevelIdArray, levelObj, lastIndex) {
      if(lastIndex >= 0) {
        this.locModService.deleteAPI(parentLevelIdArray[lastIndex], levelObj.id)
        .subscribe((response) => {
          //console.log("Inside subscribe()...");
          if (response.status === 200) {
            this.message = 'Image uploaded successfully';
            this.getSublevels();
            this.getAllLinkedLevel();
            lastIndex = lastIndex - 1;
            this.recursiveDelete(parentLevelIdArray, levelObj, lastIndex);
          } else {
            this.message = 'Image not uploaded successfully';
          }
        }
        )
      }
  }

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

Error in main.ts due to issues with importing components using an index.ts file

I am facing a common exception: Unexpected directive value 'undefined' on the View of component 'AppComponent' Many solutions I found online did not address my specific issue related to circular dependencies or missing export statem ...

Assign a specific HTML class to serve as the container within an Angular directive

Is there a way to dynamically add and set an HTML class using an Angular directive with a parameter? Let's consider a scenario where we have a div with an existing class but no directive: <div class="myClass"></div> Now, if we w ...

Navigating Unknown Properties in Angular: A Guide to Iterating Through Arrays

I'm having trouble coming up with a title for my question. I want to loop through an array of dynamic objects coming from a database, but I don't know the properties of the objects. Here's an example of the array object: [{ "id": 9, ...

NextJS compilation sometimes results in undefined errors when using Sass styles

My peace lies in the sass code: .link display: inline-table text-align: center align-self: center margin: 5px 15px font-size: 20px color: black text-decoration: none transition: 0.1s ease-in-out .link:hover text-decoration: underline .l ...

Is it possible to draw parallels between Java Callable and Angular Observable (RxJS) in terms of client implementation?

Before anyone considers downvoting or closing my question, I want to clarify that I am not asking which option is better (as this would be an irrelevant question considering one focuses on the server and the other on the browser). In this straightforward ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Having trouble installing npm packages due to an error

As I attempt to install my npm packages, a frustrating error occurs. What steps should I take to resolve this issue? npm ERR! code EINVALIDTYPE npm ERR! typeerror Error: Argument #5: Expected object but got string npm ERR! typeerror at inflatableChild ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

Getting started with Angular 2 and initializing component variables

Hey there, I'm new to angular2 and currently facing a challenge. Here's the Service section: getReports() { return this.http.get(GlobalVariable.BASE_API_URL + 'report/l', {headers: this.headers}).map(res => res.json()) ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

Typescript TypeError: Unable to call function this.array[i].greet as it is not defined

When attempting to call my function, I am encountering an error. Interestingly, everything works fine when I create just one object of someClass and then utilize the greet function. This is what does not work (someArray being an array of type someClass): ...

Combine and transform multiple hierarchical JSONs into a new format

I'm facing a challenge where I need to merge two JSON objects and convert them into a different format using TypeScript in a React project. Initially, I tried implementing this with a recursive function as well as a reducer, but unfortunately, it didn ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

npm encountered an error while trying to fetch the requested package when running ng new app

I'm working on developing a new application using the ng new app command. Everything goes smoothly until reaching the final CREATE message below. At that point, it gets stuck for hours (literally) at the "Installing packages (npm)..." stage. Eventu ...

The situation I find myself in frequently is that the Angular component Input

There seems to be an issue with a specific part of my application where the inputs are not binding correctly. The component in question is: @Component({ selector : 'default-actions', templateUrl : './default.actions.template.html&a ...

Resetting an Angular form will clear the initially selected value

My application is built using Angular 4, and I have a select element inside my reactive form setup like this: <select class="form-control" formControlName="persons"> <option value="" selected>Select default</option> <option * ...

Dynamic Material UI Timeline

I am facing a challenge with making the Timeline in Material UI responsive for the first time. Currently, I have it set to align 'alternate', but I want it to switch to align 'left' when viewed on mobile or certain screen widths. I have ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...