Running an HTTP request conditionally within combineLatest

I'm working on a combineLatest function that makes 2 http requests, but I only want the second request to be made if a specific condition is satisfied.

combineLatest([
  this.leadsService.fetchALLLeadsActivityChart(this.clientId, this.getParams(optionsCurrent)),
  this.leadsService.fetchALLLeadsActivityChart(this.clientId, this.getParams(optionsPrevious))]).pipe(takeUntil(this.chartSubscription)).subscribe(([current, previous]) => {
    if(current.meta.success && previous.meta.success){
      this.processGraphData({current: current.results, previous: previous.results});
    } 
  });

Essentially, I need the second leadsService call to execute only when:

this.selectedDateFilter.enableComparisons = true;

Can this condition be incorporated into the combineLatest block? Or should it be handled as a separate call with the first request's result stored in a variable? Your input is greatly appreciated. Thank you!

Answer №1

Here is a possible solution

mergeMap([
  this.salesService.fetchWeeklySalesReport(this.customerId, this.getParams(currentOptions)), 
  this.salesService.fetchWeeklySalesReport(this.customerId, this.getParams(previousOptions)),
])
.pipe(
  takeUntil(this.reportSubscription),
  filter(([currentData, previousData]) => currentData.meta.success && previousData.meta.success),
  switchMap(([currentData, previousData]) => this.processChartData({current: currentData.results, previous: previousData.results}))
)
.subscribe((data) => console.log(data));

Answer №2

Separate your calls into different observables and then use combineLatest to subscribe to them.

$observable1 = this.leadsService.fetchALLLeadsActivityChart(this.clientId, this.getParams(optionsCurrent));
if(this.selectedDateFilter.enableComparisons == true) {
    $observable2 = this.leadsService.fetchALLLeadsActivityChart(this.clientId, 
    this.getParams(optionsPrevious));
}
combineLatest($observable1, $observable2).subscribe([current, previous]) => {
    if(current.meta.success && previous.meta.success){
        this.processGraphData({current: current.results, previous: previous.results});
    } 
});

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

Access the properties of the encapsulated component in Vue 3, allowing for IDE autocomplete support

I have a vue3 component named MyButton which acts as a wrapper for the vuetify v-btn component. I am trying to figure out a way to make MyButton props inherit all of the props that v-btn has and also enable autocomplete feature in IntelliJ or VSCode. Is it ...

Issue: ReactJS - $npm_package_version variable not functioning properly in build versionIn the current

After trying this suggested solution, unfortunately, it did not work for my specific case. The React application I am working on was initialized with CRA version 5.0.1 and currently has a version of 18.2.0. Additionally, the dotenv version being used is 1 ...

The system encountered an issue: Unhandled error: TypeError - the variable "users" has not been defined

I encountered an issue within this Component that is not being detected by the command prompt. Dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { User } from './user.component'; import { UserService ...

Using ADAL with ASP.NET MVC and Angular for Seamless Login Experience

Currently, we have an ASP.NET MVC application in place but are looking to incorporate Angular for new frontend functions and gradually transition the entire frontend to Angular. However, at this stage, we are facing a challenge where user logins are only b ...

Encountering the error message "The argument type 'AsyncThunkAction<*>' cannot be assigned to the parameter type 'Action<any>'" while trying to utilize a custom typed useAppDispatch hook

For a live example, you can check out this link. In the process of developing a React application with TypeScript and Redux Toolkit, I have meticulously followed the guidelines outlined in the documentation. As a result, I have successfully implemented ty ...

Making @types compatible with TypeScript 2.1 in Visual Studio 2015 Update 3

The potential of TS 2.x @types is intriguing, but I'm struggling to make it work effectively! I'm using Visual Studio 2015 - version 14.0.25431.01 Update 3 My TypeScript version for Visual Studio 2015 is 2.1.4, downloaded from this link The VS ...

The transition to Angular 7 has caused complications with the Octopus deployment process

Situation Working on an Angular 4.3 project that is built using Jenkins Utilizing "octo.exe pack ..." step to package output into a NuGet package Using Octopus for deployment to IIS Issue at Hand After upgrading the project to Angular 7, encountering ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Exploring Objects using Typescript

I need help creating a mapper for objects that allows TypeScript to recognize the returned type correctly. For example: type ExampleObject = { text: string; // this object may have properties of any type number: number; }; const object: ExampleObjec ...

Include a bank account for connecting to Stripe custom accounts

Currently, I am implementing Stripe Connect using Node.js and TypeScript for a platform that facilitates payments for third-party services referred to as "partners." Our decision to utilize Stripe Connect's custom accounts gives us complete control ov ...

When adjusting the window size with the <ion-split-pane>, both the menu and router outlet disappear

When I have two ion menus and one main content (router outlet) and resize the page or switch to mobile view, the page appears blank as if the content is missing. Here is the code: <ion-app> <ion-split-pane> <ion-menu side="start" me ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Using a global CSS file in Angular can lead to large module bundles being emitted by Webpack

In our Angular application generated with angular-cli, we are utilizing various global styles and imports defined in the styles.scss file (which begins with /* You can add global styles to this file, and also import other style files */ if that sounds fami ...

The type 'Bar<T>' cannot be assigned to type 'T extends number ? number | Bar<T> : Bar<T>'

I'm struggling with this particular code snippet: class Foo<T> { x?: T extends string ? string | Foo<T> : Foo<T> } function bar<T>(): Foo<T> { const x: Foo<T> = { } return { x } } Can anyone explain why the ...

Angular library generation causing circular dependencies

Modification Required It has come to my attention that the issue of a circular dependency arises solely when utilizing a production build - ng build lib --prod My task involves creating an Angular library intended for utilization in a separate Angular pr ...

Error message: The element state is invalid. It must be editable by the user in order to be cleared. This error occurred while attempting to click and input a date on a dropdown

I'm facing an issue while trying to automate the insertion of a date in a calendar using selenium. The error message I received is as follows: invalid element state: Element must be user-editable in order to clear it. Here's the relevant HT ...

Unknown Angular component identified

I'm currently working on an application with the following structure: app |-- author |-- |-- posts |-- |-- |-- posts.component.html |-- |-- author.component.html |-- |-- components |-- |-- tag |-- |-- |-- tag.component.ts |-- home |-- |-- home.comp ...

Tips for synchronizing the value of one field in a reactive form with changes in another field

I have a reactive form below where I'm using a form builder with groups. Fig: https://i.sstatic.net/gdc7p.png Here is the HTML code of the component <div class=""> <form [formGroup]="FeedBack" (ngSubmit)="on ...

I am facing an issue where I am unable to retrieve a static variable from a global component within a subscribed component in Angular 7

I keep encountering an undefined variable issue when inside the subscribe function. import { AppSetting } from '../config/app-setting'; this.api.userLogin(this.loginForm.value.emailid,this.loginForm.value.password).subscribe( data => { ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...