Tips for ensuring that an HTTP request receives a response before moving on to the next step in Angular 7

I am currently developing an app where I need to make a GET request to retrieve data from a component. The issue I am facing is that the next step in the process is being executed before I receive a response from the service.

Below is my service file:

  getSabhaListDetailsName(sabhaMandalName: string): Observable<any> {
const sabhaListDetailsNameURL = this.rooturl + 'sabhatypebysabhaname';
return this.http
  .post(sabhaListDetailsNameURL,{}, { params: { sabha_name: sabhaMandalName } })
  .pipe(map(this.extractData),
   catchError(this.handleError<any>('sabhaListDetailsNameURL')));

}

This is the component file where I call the above service:

   this.sabhaService.getSabhaListDetailsName(element.sabha_id).subscribe(result => {
  this.tempRetrieveSabha = result.data.sabhaList;
  //return this.tempRetrieveSabha;
  //  });
  console.log(this.tempRetrieveSabha);
  this.tempRetrieveSabha.forEach(
    element1 => {
      console.log(this.tempRetrieveSabha);
      if (element1.sabha_type == element.sabha_type) {
        this.tempSabha_ID = element1.id;
        this.tempSabha_Type = element1.sabha_type;
        this.tempFollowup_ID = element.followup_id;
      }
    })
});

My question is, how can I ensure that the HTTP request finishes before looping through the array?

Answer №1

When using the Rxjs subscribe method, it will initiate an HTTP Ajax request to execute the API call. It is essential to place the Array loop within the subscribe method in the component. Additionally, could you kindly include the 'extractData' code?

Upon reviewing the current code, no issues seem to be present.

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

"JavaScript Object Notation ajax request results in an undefined

I've been searching through SO and various websites in hopes of finding a solution, but nothing seems to address my specific issue. The task at hand is to retrieve a value from a function. Currently, the data is successfully fetched from the JSON cal ...

Having trouble retrieving the "history" from props?

I am working with a React component. import * as React from 'react'; import { Component } from 'react'; import { FormControl, Button } from 'react-bootstrap'; type Props = { history: any[]; }; // Question on defining Prop ...

Interacting with an API and retrieving data using JavaScript

I have hit a roadblock. This question might be simple, but I am struggling to figure it out. I am attempting to retrieve a response from an API (mapquest), but I can't seem to navigate the response to extract the necessary information. Here is my con ...

Can you explain the functionality of `module.exports = mongoose model` in a NodeJs environment

Coming from a front-end React background, I am familiar with statements like import and exports. However, as I delve into learning Backend (NodeJs) with mongoDB, I find myself curious about the mechanics of import and export in this new environment. I hav ...

What is the best way to retrieve the date value from an input field?

I am curious about how to extract the date from an input field and compare it with a list of objects. <input type="date" [(ngModel)]="date"> I am looking for a way to retrieve the selected date value and then compare it with the dates in my list of ...

Introduction to Ajax communication using node.js

Currently, I am attempting to create a basic node.js server that takes in a request for a string, selects one randomly from an array, and returns the chosen string. However, I am encountering some challenges along the way. Here's what my front end lo ...

Unable to trigger click event on SVG path element

Hey there, I'm currently working on a project and I'm having some trouble with the click event for my SVG paths. $path.map(function(){ $(this).mouseenter(function(){ $count = $path.attr('data-like'); $('#coun ...

We apologize for the inconvenience, but please address the upstream dependency conflict before proceeding. You may also choose to use the --force or --legacy-peer

npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="532b3e2a2c3bf48d454345584b4348454242404443472c525e7d1d010f13270">[email prote ...

Connect the textchanged event exclusively when the Enter key is pressed

Q: Is there a way to trigger the TextChanged event for an asp:textbox only when the Enter key is pressed, and not when other keys are typed or when the textbox loses focus? ...

The controller's variable does not appear to be updating the user interface as expected

When the HTML page loads, I call a function within an angularjs controller (discussions()), which sets a value to a variable ($rootScope.name). Later, when I click a button on the same HTML page, it triggers a series of JavaScript functions. The final Java ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

Eslint requires that return values are used effectively

I am seeking a TypeScript or ESLint rule that enforces the usage of return values from functions. For example: const getNum = () => 12 This rule should allow me to call the function and store the returned value like this: const a = getNum() However, i ...

The stunning fade effect of Magnific Popup enhances the visual appeal of the inline gallery

I'm currently using magnific popup for an inline gallery, but I'm not seeing any effects. I would like to have a fade effect when opening/closing the popup. Can someone assist me with achieving this? https://jsfiddle.net/gbp31r8n/3/ [Check o ...

Obtain the JSON response from the servlet

Is there a way to get a JSON response from a servlet in JavaScript? I am using AJAX post to send data to the servlet. Here is my AJAX code $.ajax({ type: "POST", url: "formDelegationServlet", data: { ...

Can anyone provide assistance on implementing multiple where conditions in a loop with Firebase and Angular?

I've been attempting to implement dynamic conditions on a firebase query, but I'm having issues getting it to work. I even tried using chatgpt, but that didn't provide me with the ideal solution either. Can someone please assist me in resolv ...

Before each existing DIV in a loop, a new div is inserted using the insertBefore

const len = document.getElementById('parent').children.length for (let i = 0; i < len; i++) { const div = document.createElement("div"); document.getElementById('parent').insertBefore(div, document.getElementById('parent' ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Is it possible to implement a different termination condition when using *ngFor in Angular 2?

After countless hours of searching on Google, I have yet to discover a method for implementing an alternative stop condition for loops created with the *ngFor directive. By default, *ngFor loops end with this condition: index < array.length. Is there a ...