Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nesting?

public observable1(): Observable<Response> {
    let headers = new Headers();
    headers.append("Content-Range", "bytes */*");
    let requestOptions = new RequestOptions({headers: headers});
    return this.http.put(url, "", requestOptions);
}

public observable2(data1url): Observable<Response> {
    let headers = new Headers();
    headers.append("Content-Range", "bytes */*");
    let requestOptions = new RequestOptions({headers: headers});
    return this.http.put(data1url, "", requestOptions);
}

public observable3(data1url): Observable<Response> {
    let headers = new Headers();
    headers.append("Content-Range", "bytes */*");
    let requestOptions = new RequestOptions({headers: headers});
    return this.http.put(data1url, "", requestOptions);
}

I currently have them nested in order to chain them, but I am wondering if there is a way to achieve this without nesting them.

public doHttpProcess() {
    return this.observable1().concatMap(result1 => {
        return this.observable2(result1.json().data1)
            .concatMap(result2 => {
                return this.observable3(result1.json().data1);
            });
    });
}

Thank you for any assistance you can provide.

Answer №1

Just a little tweak needed to reach the solution - remove the second nesting and chain the concatMap calls.

public doHttpProcess() {
    return this.observable1()
      .concatMap(result1 => this.observable2(result1.json().data1).map(result2 => ({ result1, result2 }))
      .concatMap(({ result1, result2 }) => this.observable3(result1.json().data1));
}

If you can move forward without using result2 for the last observable, simplify it as follows:

public doHttpProcess() {
    return this.observable1()
      .concatMap(result1 => this.observable2(result1.json().data1).mapTo(result1))
      .concatMap(result1 => this.observable3(result1.json().data1));
}

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

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Unable to implement client-side functionalities in Angular 17 with server-side rendering

view image description hereview image description here Is there a way to make my component run on the client side, similar to "use client" in Next.js? This is my first time working with server-side rendering in Angular, and everything works fine when it&a ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

Angular: Nested FormArray not populating the values in the FormControls

I have a form that contains a FormArray inside which you can dynamically add values and in this case I can retrieve the values using the FormControl. const formGroup = this._formBuilder.group({ dataArray: new UntypedFormArray([]), }); Inside this first ...

Ensuring the proper export of global.d.ts in an npm package

I'm looking to release a typescript npm package with embedded types, and my file structure is set up like so dist/ [...see below] src/ global.d.ts index.ts otherfile.ts test/ examples/ To illustrate, the global.d.ts file contains typings ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

What is the best approach to include two ng-contents within a single template and manage them using *ngIf?

Presently, I am dealing with an Angular 2 component that is designed to showcase a Bootstrap 3 button group. This particular component has the capability of having a label or standing alone. In order to address this, I opted to utilize two ng-contents con ...

Ensure that an input field is mandatory only when another field contains a value in Angular 6

I am working with two input controls in my Angular 6 project. The first control looks like this: <input type="text" [(ngModel)]="UserData.FirstControl" formControlName="FirstControl" class="form-control" maxlength="8" > T ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Having trouble finding two p-col-6 elements side by side in the PrimeNG FlexGrid with Angular?

I have integrated Flex Grid into my Angular7 project. In the initial state, I am able to display two p-col-6 elements side by side without any issues. However, when I try to rearrange them in p-col-12, they no longer align properly. Here is a detailed expl ...

Error in Angular integrating with Stripe. No definition found for 'Stripe'. Perhaps you meant 'stripe'?

I'm currently in the process of connecting Stripe to my app with redirection, utilizing Angular and typescript. My component contains the following code snippet: var head = document.getElementsByTagName('head')[0]; var script = document.cre ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Storing numerous string labels and arrays in a TypeScript associative array

I am currently developing a mobile app using Ionic 4 where I need to store various labels and arrays in an associative array. However, I am encountering challenges when it comes to initializing the array, adding new items to it, and updating existing ones ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

The type 'TaskListProps[]' cannot be assigned to type 'TaskListProps'

I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

How does TypeScript handle the ` import Foo from "Bar" ` statement?

When you bring in a module without using a '.' or '..' prefix For instance: import File from 'FileClass'; How does the ts compiler exactly locate the 'FileClass'? The documentation states Module names can be rel ...