Perform an HTTP request using the data obtained from the previous request

I am looking to execute two HTTP requests, one GET and one POST, where the second request is based on the response from the first.

Here is the output from the initial GET call:


{
    "weekNbr": "34-2017",
    "startDate": "2017-09-16",
    "endDate": "2017-09-22"
}

The response will be modified and used as the body for the subsequent POST request in this format:


{
    "weekNbr": 34, (from initial response)
    "year": 2017 (from initial response)
}

A possible solution involves utilizing RxJS operators to handle both requests within a single service:

http.get(url1).pipe(
    map(perform manipulation)
).subscribe(
    (newObject) => {
        return http.post(url2, newObject);
    }
);

It's worth noting that these calls need to be completed within a unified service. Any recommendations on specific rxjs operators for this task would be greatly appreciated.

Answer №1

To efficiently handle two HTTP requests, one dependent on the other, you can utilize the flatMap/mergeMap operator.

For instance, consider the following implementation:

http.get(data).flatMap(res => {
    // res represents the response from the first GET request
    // manipulate the data and pass it to a POST call
    return http.post(data);
})
.map(res => {})
.catch(e => {});

Answer №2

Below is a sample of a dummy service that I have prepared:

import {of, Observable} from 'rxjs';
import {flatMap} from 'rxjs/operators';

/**
 * Example of a Dummy Service with Observables.
 */
export class MyService {

  getInformation$(): Observable<{foo:string}> {
    return of({foo:'bar'});
  }

  postInformation$(params:{foo:string}): Observable<any> {
    return of({
      fooUpperCase: params.foo.toUpperCase() // Just a demo transformation
    });
  }

  main() {
    this.getInformation$().pipe(
      flatMap(data => this.postInformation$(data)) // Process each data and return a new observable 
    ).subscribe(console.log);
  }
}

new MyService().main();

This code snippet replaces the standard HTTP observables with dummy of observables for demonstration purposes.

See live example here

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

Tips for incorporating a captcha image into your angular 8 application

I would like to implement a captcha element with an image of letters and an input field for the user, (I prefer not to use the "I am not a robot" version) similar to this example: https://i.sstatic.net/dd1Gb.png Is this feature still available today? ...

Combine TypeScript files in a specific sequence following compilation

I am hoping to utilize gulp for the following tasks: Compiling TypeScript to JavaScript, which is easily achievable Concatenating JavaScript files in a specific order, proving to be challenging Since I am developing an Angular application, it is crucial ...

Guide on initializing a Redux toolkit state with an array of objects or local storage using TypeScript

Currently, I am attempting to set an initial state (items) to an array of objects or retrieve the same from localStorage. However, I am encountering the following error. Type 'number' is not assignable to type '{ id: string; price: number; ...

Exploring Angular Performance: Template Functions vs. Properties. Which Method Reigns Supreme in Speed?

When dealing with multiple input controls that need to display a message when touched and invalid, I created a function for re-use in my form. The form contains numerous controls, so re-usability is important. isInvalid = (control: AbstractControl): boole ...

Avoiding redundancy when importing identical CSS file in multiple documents

I'm currently working on an Angular project that utilizes Sass for CSS processing, but I'm considering integrating Tailwind CSS. I'm interested in importing Tailwind into different component Sass files to build upon them, but I've notic ...

Rendering Backend Data in Angular Application on Page Refresh with Apache Server Integration

Attempting to deploy an Angular Flask Application demo with Apache. The project directory is located at /var/www/backend/basicapp/. Within this directory, you will find: app.py from flask import Flask, jsonify, render_template from flask_cors import CORS, ...

Determining the data type of a generic variable within an Angular component

I'm currently in the process of developing a versatile component that can handle data of only two specific types: interface X{ name: string, path: string, type: string, } interface Y{ name: string, path: string, } Both types X a ...

Render JSON value as an input in an Angular component using @Input()

In my app.component.html file, I have included the following template: <test [someInput]="data"></test> The 'data' variable is a JSON object property structured like this: let data = {hello: "ciao"} Below is the code from my test. ...

Instance of exported class declared in Typescript

Currently, I am in the process of developing my initial declaration file for a foreign library known as react-native-background-timer. Within this library, there exists a default export that I am uncertain about how to declare within the index.d.ts file. ...

Utilizing Sharepoint Online SPFX Web parts with React: A guide to selecting scripts dynamically based on environment requirements

Would it be possible for me to dynamically choose which script to utilize in my web component? This is how I currently have my imports set up: import * as jQuery from 'jquery'; import 'jqueryui'; Here's what I am aiming to achie ...

A guide on including all Angular Material modules in Angular 9

I am looking to incorporate all angular material modules and utilize them across all templates within my angular project. ...

Overriding Bootstrap Modals with PhaserJS Canvas

I am currently working on a simple game using phaserJs with Angular and styling it with bootstrap. The issue I'm facing is that when I display a bootstrap modal and interact with it, it affects the buttons on my phaserJS canvas. Here is an example pr ...

I am currently working on implementing data filtering in my project. The data is being passed from a child component to a parent component as checkboxes. Can anyone guide me on how to achieve this filtering process

Below is the code I have written to filter data based on priorities (low, medium, high). The variable priorityArr is used to store the filtered data obtained from "this.data". The following code snippet is from the parent component, where "prio" is the v ...

Show pictures in Angular 10 after uploading them via Multer on the Node.js server

My web application is built using the MEAN stack. I am utilizing Multer to save images in an artImages folder on my Node.js server. The post request uploads images and stores their paths along with other data in MongoDB. const storage = multer.diskStorage( ...

The function Interceptor.intercept is not defined

For a while now, I've been working on implementing an application-wide interceptor. However, no matter what I do, I keep encountering the same frustrating error: TypeError: this.interceptor.intercept is not a function After countless hours of debugg ...

Encountered an issue when trying to update information in mongodb

Error: The document with _id ObjectId('5a02f5aac293238265959fd7') has been updated, causing the (immutable) field '_id' to be changed to _id: ObjectId('5a02f7cdc0d5868391967dd5') {_id: ObjectId('5a02f5aac293238265959fd7 ...

The ngtools/webpack error is indicating that the app.module.ngfactory is missing

I'm currently attempting to utilize the @ngtools/webpack plugin in webpack 2 to create an Ahead-of-Time (AoT) version of my Angular 4 application. However, I am struggling to grasp the output generated by this plugin. Specifically, I have set up a ma ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

The issue of Angular, ng-ckeditor, and the problematic editor-destroy-iframe bug

This particular post pertains to [email protected] and is filled with information on [email protected]. Despite finding similar questions on SO, I am convinced that this remains an unresolved issue. Please refrain from marking this post as a dup ...

Stop the direct importing of modules in Angular applications

I have a feature module that declares components and also configures routing through a static function. @NgModule({ declarations: FEATURE_COMPONENTS, entryComponents: FEATURE_COMPONENTS, imports: [ UIRouterModule, ... ] }) export class Fea ...