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

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

Embarking on a new undertaking with Visual Studio 2015 and diving into the world of Angular

My journey to getting Angular2 working in Visual Studio 2015 Pro involved a lot of trial and error, but I eventually found a setup that worked for me. Despite the abundance of instructions out there, I struggled to find clear answers tailored specifically ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

What is the best way to refresh an array in a different component?

It all starts with a data response object: let response = { attachments: [{id: 1}, {id: 2}, {id: 3}] } This valuable data is utilized in the root component <app-root></app-root> <app-documents [response]="response"></app- ...

Creating a Vue.js component during the rendering process of a Laravel Blade partial view

In my Vue.js project, I have a component that is used in a partial view called question.blade.php: {{--HTML code--}} <my-component type='question'> <div class="question">[Very long text content...]</div> </my-component& ...

Retrieve data using Angular FileReader's onloadend method and return the result

When working with audio recording in Angular, I encountered a challenge with my code. The goal was to record audio, obtain the blob, and convert it to base64 using FileReader. However, I struggled with returning this base64 data from the onloadend method o ...

What could be the reason for a querySelector returning null in a Nextjs/React application even after the document has been fully loaded?

I am currently utilizing the Observer API to track changes. My objective is to locate the div element with the id of plTable, but it keeps returning as null. I initially suspected that this was due to the fact that the document had not finished loading, ...

Upon clicking the 'Add Image' button, TINYMCE dynamically incorporates an input

I am in search of creative solutions to address an issue I'm facing. Currently, I am utilizing TINYMCE to incorporate text into my webpage. However, I would like to enhance this functionality by having a feature that allows me to add an image along w ...

Problem encountered while downloading dependencies with Snyk

While attempting to set up the dependencies for the W3C Respec project, I encountered this error message: npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for build steps and `pr ...

Upgrading from Angular 5 to 6: Embracing the RxJS Changes without the crutch of rxjs

Currently, I am facing the challenging task of migrating a project from Angular 5.2.11 to version 6.0.0. The main issue I'm encountering is with RxJS 6 (which is essential for Angular versions above 6). Here's an example of one of the errors that ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Angular 13: How to Handle an Empty FormData Object When Uploading Multiple Images

I attempted to upload multiple images using "angular 13", but I'm unable to retrieve the uploaded file in the payload. The formData appears empty in the console. Any suggestions on how to resolve this issue? Here is the HTML code: <form [formGro ...

Access account without providing all necessary identification documents

I'm currently facing an issue with my User Schema, as I initially defined 3 inputs for name, surname, and email. However, I now want to allow users to log in only with their email and password, without having to input their name and surname. How can I ...

Tips for extracting data from JSON values

My JSON Data Display let foodData = [{ meal_com_id: "1", name_company: "PeryCap", image: "https://shopgo.in/upload/1545849409-1518284057-Untitled-nn1.png", status: "1", description: "sdvaebfvhjaebfber itnwiuore tg5ykrgt wiretgi34 tgi3rgt ...

Tips for displaying the date of a JSON response in Angular HTML format?

When working with Angular HTML, I am looping through a JSON array using ngFor and accessing the birth date data like this: <td>{{item.customer_info.birth_date}}</td> The data is being displayed as ddMMyyyy format, but I would like to change it ...

Iteratively modify each essential attribute of a JSON object

In my data set, I have moisture levels recorded at various timestamps in a JSON object: { "values": { "21-Aug-2020 20:28:06:611591": "58.59", "21-Aug-2020 20:28:09:615714": "71.42", "21-A ...

Utilize user input to fetch data from an external API

Let's say there is a field for 'part number' input that is not enclosed in a form tag. Whenever a user enters a value, the onblur event or a button positioned next to the input field should trigger a query to an external site via its API and ...

Using Node.js to alter an existing JSON file

I have a file named a1.json that contains the following data: { "Key1" : [ { "Key11" : "Value11" , "Key12" : "Value12" }, { "Key21" : "Value21" , "Key22" ...

Insert a picture within the text input field

I'm facing a specific scenario where I need to add text followed by an image, then more text followed by another image and so on. Please see the input text with values in the image below. Can someone guide me on how to accomplish this with jQuery and ...

What is the best way to center all items in a vertical list of text?

Having trouble aligning elements in my Angular app - specifically date, file total, and file size. When one number has more digits than the others, it throws off the alignment. I've attempted adjusting padding margins and using display properties lik ...