Executing a series of sequential HTTP calls in Angular can be achieved by chaining

Is there a way to create a function that can make HTTP calls one after the other, allowing me to use the response from the first call in the second call? For example, retrieving the user's IP address from the first call and then using that IP address to register the user in the second call.

Here's a demonstration of what I am trying to achieve:

registerUser(user: User) {
    this.utility.getIpAddress()
    .subscribe(data => {
        this.ipAddress = data.ip;
    });
    const body = {
        UserName: user.UserName,
        Email: user.Email,
        //...
        UserIP: this.ipAddress,
    }
    return this.http.post(this.registerAPI, body);
}

Answer №1

To implement this functionality, you can utilize the switchMap operator from RxJS 5.5+ pipeable operators.

import { switchMap } from 'rxjs/operators';

registerUser(user: User) {
  return this.utility.getIpAddress().pipe(
    switchMap(data => {
      this.ipAddress = data.ip;

      const body = {
        UserName: user.UserName,
        Email: user.Email,
        UserIP: this.ipAddress,
      };

      return this.http.post(this.registerAPI, body);
    })
  )
}

If you are using RxJS version lower than 5.5:

import { switchMap } from 'rxjs/operators';

registerUser(user: User) {
  return this.utility.getIpAddress()
    .switchMap(data => {
      this.ipAddress = data.ip;

      const body = {
        UserName: user.UserName,
        Email: user.Email,
        UserIP: this.ipAddress,
      };

      return this.http.post(this.registerAPI, body);
    });
}

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

Retrieve particular items from the API response

What is the best way to access a specific object based on a property from an API response? In my scenario, I have an array of Products retrieved properly from my server. The watchedProducts class has a property called productId which corresponds to the id ...

Maintain the Http Connection request header active when using Angular with Spring Security

During the process of converting my AngularJS project into Angular 4, I encountered an issue with maintaining the Http connection after logging into the application. The request I am making is: POST /myapp-services/login.html?username=admin&password= ...

Eliminating TypeScript errors when flattening nested objects

We are facing a challenge in our company with the editing form. One of our team members unilaterally changed the format of the API payload return, causing us to fall behind and play catchup. Unfortunately, the API calls we need to make do not support nest ...

At the moment of execution, the imported npm package module is not defined

Recently, I added a package named "js-linq" (available at https://github.com/battousai999/js-linq) using the command npm install js-linq and it seemed to install successfully. This process is clearly outlined in the npm documentation at https://www.npmjs.c ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

Ag-grid's external filtering feature allows users to easily apply

Initially, I attempted to integrate an external filter, but encountered issues where it wasn't functioning properly, resulting in the grid being stuck in a loading state. As a result, both the filter and grid are currently inaccessible. Currently, I ...

Angular, Ag-Grid, Issue involving Jquery

After implementing the datepicker function exactly as specified in the example code on Ag-Grid documentation, I encountered an issue when enabling editing for date columns. The error pointed to the line $(this.eInput): ERROR TypeError: __WEBPACK_IMPORTED_ ...

Joining the Parent Route String with a Variable using Angular Routerlink

How can I incorporate string interpolation or concatenation into the router link below in order to navigate to the parent route and include a variable link? <a routerLink="../account-information/{{item.productId}}"> ...

Is it possible to leverage ES6 modules within a Node.js application while also debugging it using Visual Studio?

Trying to create a basic node.js module test project using ES6 in Visual Studio 2015 has resulted in build errors, preventing me from running or debugging the application. Could it be that I arrived at the party too soon? I attempted opening and building ...

how can I update a class of an element when the input box is disabled in angular?

Is there a way in Angular to change the class of a separate element (calendar icon button) when it detects that an input textbox is disabled? I have a disabled input type textbox and I want the class of the calendar icon button to be changed based on its d ...

Error 404: Node Module Dependency Not Found - npm Unable to Locate package.json

I recently duplicated the angular module from https://github.com/SebastianM/angular-google-maps into my private github repository, and now I'm attempting to install and utilize the fork. Here are the steps I followed: npm install my-repo\angula ...

I'm having trouble retrieving my variable within the socketcluster's socket.on function

How can I store the value of msg in the variable sample when sample is not accessible inside the callback function? import { Injectable } from '@angular/core'; import * as socketCluster from 'socketcluster-client'; @Injectable({ pro ...

Is there a way to access the name of a generic type T class in TypeScript?

I'm currently working on incorporating the Service Locator pattern into my TypeScript project. Below is the snippet of my code: //due to only partial knowledge of TypeScript private static serviceMap: Map<string, any>; public static get& ...

Angular 5 - Issue with Dynamic Routing not Functioning as Expected

After setting up a new project and making modifications to the routing module for dynamic routing, I encountered an issue with one of my routes: Below is the updated routing module code snippet: import { NgModule } from '@angular/core'; import ...

Using functional components in Redux without the need for React

I have a functioning component that does not use React, but utilizes Redux as shown below: export const isAuthenticated = () => ({user}) => { console.log("user : ", user); return true; }; const mapStateToProps = (state) => { ...

When a file is modified in Angular, it triggers an error prompting the need to restart the 'npm' service

Whenever I make changes to a file in my Angular application, I encounter the following error: ERROR in ./src/app/@theme/components/auth/index.js Module build failed: Error: ENOENT: no such file or directory, open 'C:\Dev\Ng\ngx-a ...

The global class variable encounters an error when trying to assign the value of "socket" to it

Within my class constructor, I am setting up a Socket connection and then storing the socket parameter in a global class variable (this.socket_variable = socket) so that I can access it across all functions in the class. CODE const { Server } = require(&q ...

Inserting items into arrays in Angular

I've encountered an issue with pushing an object into an array. The array contains objects, and this component is responsible for displaying them: <div class="row" *ngFor="let element of dietList"> {{element.name}} {{ element.weight }} </d ...

Encountering an issue with Google Auth0 stating that the module "@auth0/nextjs-auth0" does not have the exported member "UserProvider"

I am currently working with next.js and typescript, and I want to incorporate Google Auth0 for authentication. However, I encountered an error: Module '"@auth0/nextjs-auth0"' has no exported member 'UserProvider'. I tried sea ...

Sending data into Angular components

My experience with Angular development is still relatively new. I am currently working on a website for a construction company, where I have implemented three different components on a single page. Here is an overview of the current setup and what I aim t ...