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

React Native: Once a user has successfully logged in, I would like the app to automatically direct them to the "Home" screen

After a user signs in, I would like my app to navigate home. However, it seems this is not working because the roots have not been updated. You can view the App code here to get a better understanding of what I am trying to communicate. What is the most e ...

A more efficient method for incorporating types into props within a functional component in a TypeScript-enabled NextJS project

When dealing with multiple props, I am looking for a way to add types. For example: export default function Posts({ source, frontMatter }) { ... } I have discovered one method which involves creating a wrapper type first and then defining the parameter ty ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

Using Angular 2's ngFor directive to iterate through arrays with access to first, last

In this example, I am attempting to make the first occurrence the default: plunkr However, I encountered the following error: Unhandled Promise rejection: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

ServiceWorker has responded with a 503 OK status code

Recently, I implemented @angular/service-worker to create a SW for my angular4 web application. However, I encountered an issue after updating the ngsw-manifest.json file to handle dynamic requests from the server - now, whenever I go offline (after initia ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

What is the return type of the Array.prototype.sort() method in Typescript?

I have created a custom type for arrays that are considered "sorted" like this: type Sorted<T> = T[]; This serves as a reminder for developers to provide a sorted array of any type and ensure the sorting themselves. Although I understand that Types ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Ways to attach an event listener to a useRef hook within a useEffect hook

As I work on creating a custom hook, I am faced with the task of adding an event listener to a ref. However, I am uncertain about how to properly handle cleaning up the event listener since both listRef and listRef.current may potentially be null: const ...

Allow Ionic to exclusively work on Android smartphones

When developing an app using Ionic for iOS, you have the option in Xcode to easily specify if the app should be compatible with iPhone, iPad, or both. Is there a similar feature available for Android where I can limit the app's availability based on ...

Format Currency Fields with Comma Separated Values in Angular and Material UI

In our Angular 9 project, we are implementing currency input fields that require a standard masked label displaying a comma separated format. When the user enters 56000.55 into the input field, upon blur event, we need to show 56,000.55 as a comma separat ...

Exploring the world of Typescript TSX with the power of generic

Introducing JSX syntax support in Typescript opens up new possibilities. I have an expression that functions smoothly with traditional *.ts files, but encounters issues with *.tsx files: const f = <T1>(arg1: T1) => <T2>(arg2: T2) => { ...

Problem Encountered in Angular 4 CLI when using enableProdMode in Internet Explorer 11

Currently, my Angular 4 application built using NodeJS works flawlessly on Internet Explorer 11 and the latest versions of Chrome and Firefox during development. However, when I enable Production Mode in the NodeJS Build as shown in the example from packa ...

Issue with Angular 2 Teamcity Error

Hey team, I'm encountering an error in TeamCity and could use some assistance. [05:40:13][Step 1/6] Update assembly versions: Scanning checkout directory for assembly information related files to update version to 12 [05:40:13][Step 1/6] scan: Search ...

Collaborate on a component used in multiple modules

In my application, there are two modules: employer and landing. I have created a component in the landing module that I want to share with the employer module. To achieve this, I declared the component in the app.module.ts file of the parent module and use ...

What is the process of extending a class in TypeScript?

I have a few services that contain the same code: constructor (private http: Http) { //use XHR object let _build = (<any> http)._backend._browserXHR.build; (<any> http)._backend._browserXHR.build = () => { let _xhr = _ ...