Utilizing Angular-dependent subscriptions in conjunction with forkJoin for efficiently modifying and processing data within code blocks

I have a subscription that relies on the outcome of a previous subscription. I am utilizing forkJoin to avoid nesting them:

this.service.service1().pipe(
    flatMap((res1) => this.service.service2(res1))
).subscribe((res2) => {
    // Perform actions with res2.
});

The challenge is that I need to alter the data before calling the second subscription. My goal is to do something along the lines of:

this.service.service1().pipe(
    flatMap((res1) => {
      // Modify res1 data here.
      // Make 2nd Api Call
      this.service.service2(res1)
    })
).subscribe((res2) => {
    // Do something with res2.
});

Is there a different operator/syntax I should use to accomplish this or can I tweak this approach?

Answer №1

Make sure to return an observable from your flatMap. Using the syntax this.service.service2(res1); achieves the same result as shown below.

this.service.service1().pipe(
    map(res1 => //modify resp1 here)
    flatMap((modifiedRes1) => this.service.service2(modifiedRes1)) // note the lack of brackets, indicating that we are returning the observable instead of void.
).subscribe((res2) => {
    // Perform operations on res2.
});

It's important to understand the distinction between:

(res1) => this.service.service2(res1)

and

(res1) => {
  this.service.service2(res1)
}

The first function returns an observable, while the second one returns void.

(res1) => this.service.service2(res1)

is equivalent to

(res1) => {
  return this.service.service2(res1)
}

Using {} creates a block where a return statement is necessary when used in an arrow function.

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

Maintaining the ngFor value when clicked and passing it to another component

Currently tackling an angular project and seeking assistance with a particular issue... I have successfully displayed data from an array, but now I am looking to store the value of the element I click on so that I can utilize it in another component along ...

Tips for filling a three-tier nested Formarray in Angular

I have implemented a nested form array structure in Angular with three levels. The first level is 'person', followed by 'fir detail' (employees), and within that, I have 'act detail' (employee skill) form array. While I am ab ...

Is it possible in Typescript to determine whether an object or function was brought in through an "import * as myImport" declaration?

Currently, I am importing all exports from a file in the following way: import * as strings from "../src/string"; After that, I assign a function to a const based on a condition: const decode = (strings._decode) ? strings._decode : strings.decod ...

What is the best way to globally trigger a ModelChange event in Angular using jQuery? Alternatively, how can we use jQuery to alert Angular of any changes

My goal is to replace all date and time inputs on a page with a jQuery date time picker. I decided to use jQuery in order to avoid asking developers to change their code and replace existing components. Instead, the jQuery code will replace the date and t ...

The method Office.context.mailbox.item.internetHeaders.setAsync has not been configured

I am integrating the Microsoft Office API into Outlook. I'm attempting to add an extra x-header to my email in the composer scope for later identification. To achieve this, I referred to the following documentation: https://learn.microsoft.com/en-us/j ...

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

Using FormControl Inheritance in Angular 4

My goal is to enhance the functionality of a FormControl by creating a subclass with additional properties. These properties will then be utilized in custom form controls to modify behavior. I attempted to inherit from FormControl (let's call it Stan ...

Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise. I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at t ...

Receive a 500 error when trying to express post without using a router or subs

Here is the setup I am working with: When a user posts to /register, the server will use Passport and Mongoose to register the user. If there is a UserExistsError, the server sends this information to the client through HTTP error handling. However, the ...

What are the steps for modifying the fields within the form?

The HTML code displays a table of todo items with options to delete or edit each entry. <tr *ngFor="let todo of todos; let i=index"> <td>{{ todo.name }}</td> <td>{{ todo.designation }}</td> <td>{{ todo.compa ...

Ways to incorporate a notification feature with an icon or image

I'm looking to create a visually dynamic icon/image similar to mobile device notifications, but primarily for desktop use. This image will be positioned before some text. For instance: https://i.sstatic.net/MHocy.pngSome Text This design features tw ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

The step-by-step guide to launching a server using Firebase Cloud Functions

After following a tutorial to set up an express server for accessing a MongoDB instance on Google Cloud Platform, I encountered an issue when deploying my Firebase functions. When I run the command firebase deploy --only functions All functions deploy su ...

New design options for angular2 login page

My website typically has a standard layout with a tool and sidebar on all pages, however I want to ensure that they are not visible when the user navigates to the login or register page. In AngularJS, this was easily achieved using ui-router to define a sp ...

The 'input' element does not recognize the property 'formControl', causing a binding issue in Angular Material Autocomplete with Angular 12

Recently, I upgraded my Angular app from version 11 to 12 along with all the dependencies, including Angular Material. However, after running 'ng serve', I encountered the following error: Error: src/app/components/chips/chips.component.html:19:1 ...

The webpack task has failed because it cannot read the property 'forEach' of an undefined object

Encountering errors during the build process of a jhipster project when running ./gradlew in the project's directory. Starting a Gradle Daemon (subsequent builds will be faster) > Task :webpack > <a href="/cdn-cgi/l/email-protection" class ...

Showing nested arrays in API data using Angular

I would like to display the data from this API { "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", & ...

The return type in Typescript is populated with a generic type name that lacks meaningful

When utilizing ts-results-es, I encounter an issue. This library aids in wrapping errors within a class to provide insight into potential function errors. Here is a simplified class definition: interface BaseResult<T, E> {} class Err<E> imple ...

What does the error message "JSON.parse: unexpected character at line 1 column 1 of the

In the process of developing a node.js module that involves importing a JSON file: const distDirPath = "c:/temp/dist/"; const targetPagePath = "c:/temp/index.html"; const cliJsonPath = "C:/CODE/MyApp/.angular-cli.json"; const fs = require('fs'); ...

The ngFor directive in Angular should be used with the Filter pipe to ensure that

Having a Filter implemented in my Angular Project that fetches data from Firebase. The current status in the Filter is as follows: Name 1: Lea Muster Name 2: Bruno Mustermann Name 3: Lea Muster Name 4: Gabriela Musterfrau The goal is to show duplicate e ...