How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a subscription, but I am facing an issue where method two continues its work without waiting for the api call to finish first. Can someone please help me identify where I might be making a mistake?

 getPerson() {
    this.setSelectedFlag() --> After this finishes, continue with the method
    this.personArray = this.form.controls.person.value;
    this.personArray .forEach((id) => {
      if (!this.personMap.has(id)) {
        this.loading.start();
        this.api.getpersonsData({
          id,
        }).subscribe((response) => {
          this.personMap.set(id, response);
          this.loading.stop();
        });
      }
    });
    this.personMap.forEach((person, id) => {
      if (!this.personArray.includes(id)) {
        this.personen.delete(id);
      }
    });
  }

  setSelectedFlag() {
    this.personArray = this.form.controls.person.value;
    this.personArray.forEach((id) => {
      if (!this.setFlagForPerson.has(id)) {
        this.personArraySaving.ids.push(id);
        this.api.setSelectedForPerson({
          body: this.personArraySaving,
        }).subscribe({
          next: (data) => {
            console.log(data);
          },
          complete: () => {
            return --> I expected this to signal its completion
          },
        });
      }
      });
    
  }

Answer №1

By utilizing promises in your code, you can enhance the functionality of setSelectedFlag() by returning a promise. This allows for seamless continuation of the code within getPerson()

getPerson() {
 this.setSelectedFlag().then(() => {
      // continue with the rest of the code.
 })
}


setSelectedFlag(): Promise<void> {
    return new Promise((resolve) => {
            ....
           complete: () => {
             resolve();
           }
    })
}

Visit Mozilla Developer Network to learn more about Promises.

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

Exploring Angular's AG Grid ToolTips

I am encountering an issue while trying to implement AG Grids ToolTip functionality. Following the example provided at https://www.ag-grid.com/documentation/angular/component-tooltip/#example-custom-tooltip-component, I attempted to import { ITooltipAngula ...

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

The call to the hook is invalid. In order to use hooks, they must be called within the body of a function component in

So, in my upcoming application, I am incorporating the react-google-one-tap-login library which features the useGoogleOneTapLogin hooks that need to be invoked within a React component. However, when I attempt to use it in this manner: func() { useGoogle ...

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

Error: Angular 6 and karma have encountered a problem - "Unable to load "@angular-devkit/build-angular", as it is not recognized."

Upon upgrading to the latest version of Angular, my karma tests ceased functioning and started crashing with this error log: 14 04 2018 14:17:00.453:ERROR [preprocess]: Can not load "@angular-devkit/build-angular", it is not registered! Perhaps you ar ...

What could be the reason for my React/HTML select element occasionally failing to display the default selected value?

I am currently working on creating a select element in Reactjs/HTML and I am facing an issue with setting a default value based on a component variable. Essentially, the default value of the select should be the id of a component. This is my current imple ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

Using TypeScript to assign values to object properties

In myInterfaces.ts, I have defined a class that I want to export: export class SettingsObj{ lang : string; size : number; } Now I need to reference this class in another file named myConfig.ts in order to type a property value for an object called CO ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

What is the best way to pass a value back to the main function from an async.eachOfSeries function?

Currently, I am utilizing the async npm library in my project. I am interested in finding a way to return the value of 'someVar' back to the main function. The documentation indicates that it returns a promise if a callback is not provided. Howe ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

Converting Angular 2/TypeScript classes into JSON format

I am currently working on creating a class that will enable sending a JSON object to a REST API. The JSON object that needs to be sent is as follows: { "libraryName": "temp", "triggerName": "trigger", "currentVersion": "1.3", "createdUser": "xyz", ...

Dynamically attach an Angular 2+ directive from a component

Looking to dynamically attach a directive from a component based on a condition. My attempt using @HostBinding doesn't seem to be working. import { Component, Directive, HostBinding } from '@angular/core'; @Component({ selector: &apos ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

Sending data using Ajax to the server-side code in ASP.NET

Struggling to successfully pass a series of values through Ajax to a code-behind method in order to insert the data into a database table. However, encountering issues where string variables are being received as empty strings and int variables as 0. The ...

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...