What is the best way to combine two responses and call them in a specific order, where the second http request is dependent on the response from the

After receiving the code, I am attempting to extract a combined value from two HTTP calls

defer(() => {
                return this.service.save1(data)
                    .pipe(
                        concatMap((result) => {
                            if (result) {
                                return of({
                                    ...result,
                                    c: this.service.save2(result.id , this.obj).subscribe()    
                                })
                            }
                            return of({});
                        }),
                        catchError(err => throwError(err)),
            }).subscribe((result) => {
                if (result) {
                    console.log(result);
                }
            },

In the console.log(result), we now have the complete object result with additional data under c: My goal is to include all fields returned by the initial call along with c: as an array of objects

Answer №1

There is no need to subscribe within the operators. Simply return the observable directly and subscribe where necessary.

  1. Utilize the filter pipe to disregard undefined responses from the initial request. This eliminates the need for if conditions inside the concatMap and subscription.
  2. Add a map pipe to the second observable in order to merge both results.

Give this approach a try:

return this.service.save1(data).pipe(
  filter((result) => (!!result))   // Only proceed if `result` is defined
  concatMap((result) =>
    this.service.save2(result.id, this.obj).pipe(
      map((c) => ({
        ...result,
        c: c
      }))
    )
  ),
  catchError(err => throwError(err))   // The use of `catchError` is currently redundant
);

Answer №2

Enhance the response by utilizing the output of the observable c. No subscription is necessary as it will automatically subscribe to the value using concatMap.

 defer(() => {
    return this.service.save1(data)
        .pipe(
            concatMap((result) => {
                if (result) {
                    return this.service.save2(result.id , this.obj).pipe(
                            map((data) => [...data, result]) // Utilize all available data 
                                                             // for custom formatting
                }
                return of({});
            }),
            catchError(err => throwError(err)),
}).subscribe((result) => {
    if (result) {
        console.log(result);
    }
},

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

Learn how to securely download files from an Azure Storage Container using Reactjs

I'm currently working on applications using reactjs/typescript. My goal is to download files from azure storage v2, following a specific path. The path includes the container named 'enrichment' and several nested folders. My objective is to ...

Angular allows users to click on elements that have been dynamically added to the Document Object Model (DOM), such

Incorporating the ngx-bootstrap datepicker into my project was a game changer. I have a submit button positioned below the datepicker, and I have a specific goal in mind. I want the submit button to become active as soon as I select a date from the datepic ...

Angular components are persisting instead of being destroyed

When navigating to a new page in my Angular application, I've noticed that the component from the previous page remains in memory instead of being destroyed. This results in a new instance being created when I navigate back to that page. The applicat ...

Learn how to configure an Angular2 Template Driven form element by implementing two-way binding and integrating template driven form validation techniques

Can anyone help me figure out the correct way to set up an Angular template driven form element for both validation and two-way binding? I've tried using ngModel in different ways, but cannot seem to achieve two-way binding without encountering issues ...

Firebase and Nx: Encountering issues with running emulators

I've been attempting to launch the Firebase emulators within the Nx workspace. Initially, I added firebase to my project: npm install firebase @angular/fire --save nx g @angular/fire:ng-add // configures the package in the project (unsuccessful) ng ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

"Bootstrap's modal-backdrop element presents a striking fade effect as it

Issue I am facing a problem related to Bootstrap, specifically with a modal in my HTML file. Whenever I call the modal, it appears with a fade-in effect. The code for my modal: <div class="modal fade" id="exampleModal" tabindex=& ...

Mapping intricate entities to intricate DTOs using NestJS and TypeORM

Currently, I am using the class-transformer's plainToClass(entity, DTO) function to transform entities into DTO objects. In addition, I have implemented the transform.interceptor pattern as outlined in this source. I make use of @Expose() on propert ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

Angular: StaticInjectorError(ExplorationEditorPageModule)[Number]

Currently in the process of transitioning oppia's codebase from AngularJS(1.x) to Angular(2+). I recently migrated a service called UtilsService.ts to the following code snippet: import { Injectable } from '@angular/core'; import { downgrad ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

"I am facing issues with Nodejs $lookup as it is not producing the

I am looking to merge two document collections. The first collection, "prefix," contains an array of category IDs under the categoryId key, while the second collection, "categories," holds objects with a unique _id field. Here is my sample database structu ...

Angular2: Filtering an array based on the presence of items in another array

Looking to selectively filter out entries from an object array based on certain id values within another array. I've experimented with different methods but haven't found a solution that works yet. List of id´s: list = [1,3] Array to be filte ...

Connect a pre-existing role to AWS Lambda using the AWS Cloud Development Kit (CDK)

Seeking to assign an existing role to a lambda function created with CDK Here is what I am attempting: const role1 = iam.Role.fromRoleArn(this, 'Role', 'ARN', { mutable: true, }); const lambda1 = new lambda.Function(thi ...

Incorporate Third-Party Plugins with Angular

I am interested in integrating 3rd party JavaScript plugins such as Typed.js, AOS.js, mo.js, and more into my application. However, I am still trying to understand the proper way to utilize these plugins effectively. Despite some of them having good docume ...

The issue with Ionic 2 and Angular 2 is that the http Headers are not getting included in the request

I'm currently working with the latest beta release of Ionic and I've encountered an issue with sending headers along with an HTTP POST request to my API server. The code snippet I used is as follows: ** Ionic version - Beta-8 & Angular version -r ...

Using Laravel's CSRF tokens in an Angular form

Currently working on an app that uses Angular for the frontend and the Laravel framework for backend functionalities. Can anyone share insights on how to set up a @csrf input in an Angular form for making a POST request via AJAX? Any tips or suggestions ...

Creating a custom type in Typescript using a function for testing purposes

I have been exploring ways to limit my search capabilities to specific criteria. Let's say I have a model and some data like the following: interface UserModel { _id: string; username: string; party: UserPartyModel; } interface UserParty ...

Display a JSON file within an Angular application using HTML

I have a JSON (link to the JSON) that I want to display in an html file. JSON: { "recipes": { "FRYING": { "Anchovies": [ [ {"500": "thawing"} ], [ {"60": "nothing"} ] ], "Codfis ...

When attempting to add custom webpack configuration, you may encounter an issue where the function get

I've been following a informative tutorial on integrating brotli with an Angular project. I created a `custom-webpack.config.js` file and placed it in the root directory where `angular.json` is located (also attempted to put it in the src folder, but ...