The RxJs iif() function is failing to subscribe to the specified observable

Below is the code I'm using to subscribe to function1, and based on the result (saleAgreed), I then want to subscribe to a second observable - either function2 or of(undefined). Check it out:

this.apiService.function1(id).pipe(
        switchMap(async (saleAgreed: boolean) => {

          // Waiting for user input
          let cancelAgreedSale = await this.promptSaleAgreedCancelDetails();

          // Both evaluating as true   
          console.log(`sale agreed: ${saleAgreed}`)
          console.log(`cancelSaleAgreed: ${cancelAgreedSale}`)

          iif(
            function() {
              if (saleAgreed && cancelAgreedSale) { 
                this.removeSaleAgreedRequest = { 
                  contactId : this.cid, 
                  details : this.cancelSaleAgreedDetails
                };
              }
              return saleAgreed && cancelAgreedSale;
            }, this.apiService.function2(this.removeSaleAgreedRequest), of(undefined));

          // Thought returning the observable might help, but doesn't make a difference whether 
          // it's here or not
          return this.apiService.function2(this.removeSaleAgreedRequest)
        })
      ).subscribe(res => { 
        // Returns either undefined or an observable if I return one above
        console.log(res)
      }, error => { 
        console.log(error.error)
      })

function2 implementation:

public function2(request: RemoveSaleAgreedRequest): Observable<any>  { 
    console.log('api func hit!')
    return this.http.patch<any>(this.apiUrl + 'some/endpoint', request);
  }

I believe that my code should assess the outcome of the anonymous function passed to iif(). If it evaluates to true, then function2 should be subscribed to, otherwise it should subscribe to of(undefined). While function1 is successfully subscribed to, even though my anonymous function evaluates to true, function2 is not being subscribed to. Can you point out where I'm going wrong? Thank you!

Answer №1

Calling the iif operator as a function will not work. It returns an Observable that needs to be subscribed to, preferably within your pipe.

Marking the callback as async may cause issues. Returning an Observable wrapped in a Promise might not be handled correctly by RxJS. Using both async and Observables is often unnecessary. Try using from() to wrap the call to

this.promptSaleAgreedCancelDetails()
.

To process the result of

this.promptSaleAgreedCancelDetails()
, use a switchMap. This switchMap logs two variables and employs a regular if/else statement to handle the logic.

this.apiService
  .function1(id)
  .pipe(
    switchMap((saleAgreed: boolean) => {
      return from(this.promptSaleAgreedCancelDetails()).pipe(
        switchMap((cancelAgreedSale) => {
          console.log(`sale agreed: ${saleAgreed}`);
          console.log(`cancelSaleAgreed: ${cancelAgreedSale}`);

          if (saleAgreed && cancelAgreedSale) {
            this.removeSaleAgreedRequest = {
              contactId: this.cid,
              details: this.cancelSaleAgreedDetails,
            };
            return this.apiService.function2(this.removeSaleAgreedRequest)
          } else {
            return of(undefined)
          }
        })
      );
    })
  )
  .subscribe(
    (res) => console.log(res),
    (error) => console.log(error.error)
  );

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

Guide to linking switchMap operators with feature bodies in RxJS version 6

I am currently working on upgrading my mobile app, which is built with Ionic and Angular. I need to migrate from rxjs 5.5 to rxjs 6, but I have encountered some challenges, especially in the way operators are handled within the pipe-chain. The migration do ...

The async validator in Angular will only activate upon submission if the user has made changes to the form

In my angular 10 application, I have implemented a login form with various validation checks for the username and password fields. These validations are carried out using an async validator that is applied to the formgroup containing the username and pass ...

The production build failed following the upgrade to ag-grid version 22.1.1

Since version 18, I have been utilizing ag-grid, and I am currently on version 20.0.0. I am now in the process of upgrading to the latest version - 22.1.1. After addressing warnings/errors caused by breaking changes, everything seems to be working fine, ...

Combining Keycloak with Azure B2C for identity management and implementing the authorization code flow

My current challenge involves integrating Keycloak with Azure B2C using authorization code flow. I have my Keycloak instance deployed as an Azure App Service, along with an Azure B2C tenant and a demo SPA app that I am attempting to authenticate through Az ...

Tips on Resolving TypeError: Unable to Access Undefined PropertyAre you encountering a

I'm currently facing an issue while writing unit test cases using Jest in my Angular project. Whenever I attempt to run my test file, the following errors occur: TypeError: Cannot read property 'features' of undefined TypeError: Cannot read ...

Tips on ensuring all fields are mandatory in a form

Currently, I am in the process of working on my Angular2 project. Specifically, I have created a form and my intention is to make all fields required. However, I encountered an issue when attempting to make the Title field mandatory as it is not displaying ...

Tips for managing transitions when the indicator is clicked by the user

I'm looking for a way to implement logic that determines whether or not a user can change the step by clicking on the indicator (the step number). I need a callback function that triggers every time there is a step change, but also allows me to preven ...

Issue with Static Injector: GameService cannot be injected with HttpClient in the AppModule

I'm encountering an issue with a library I created in Angular. The library makes API calls using HttpClient, but when I try to access a class from the library called GameService, I receive an error message: "Error Static Injector: StaticInjectorError( ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

Exporting keys of objects one by one

I am trying to mock the `fs` module in vitest using [memfs](https://github.com/streamich/memfs). To do this, I have created a mock file located at `./__mocks__/fs.ts` where I have set up the mocked volume and fs. However, I am facing an issue with the moc ...

Troubleshooting Ionic 4 IonSlides slideTo and getActiveIndex functionalities encountering issues within IonTab context

I am encountering an issue with my ion slides setup on a page. Here is the code snippet: <ion-slides #schemasliderref [options]="schemaSliderOpts" (ionSlideDidChange)="slideChange()"> <ion-slide *ngFor="let schemaImage of schemaImages; let i ...

Tips for combining several fields with rowspan grouping in a primeng table

Utilizing the Primeng data table for grouping rows and columns has been quite helpful. However, I have encountered a limitation where I can only group one field at a time based on the example provided on the official site. Here is the HTML code snippet th ...

No matter the circumstances, the "Unexpected end of form" error consistently appears when attempting to upload files in Express

I'm facing a challenge in implementing a file upload API endpoint for my Express+no-stress+Typescript application. Initially, I attempted to use the express-fileupload library, but I quickly realized that it didn't integrate well with Typescript ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

Angular integration with Fine Uploader

I am facing a challenge in incorporating the fineuploader library into Angular 4. A post on provided some insight, but it seems to be aimed at Angular 2. Given the updates in Angular since version 4, I require further guidance. Returning to my issue: Fin ...

Firebase login success callback not getting invoked

I have set up routes, the AuthGuard, and Firebase login in my project. I am using callbacks to handle the success and failure of the Firebase login process. successCallback(signInSuccessData) { console.log("Received with Success!"); } errorCallback(e ...

Is it possible to include the term 'public' exclusively within a .ts file in a TypeScript TSLint React environment?

I'm struggling to understand why I am encountering an error in VSCode while working on a react typescript project with tslint setup. The error message states: 'public' can only be used in a .ts file. [Also, I'm wondering why I' ...

The constructor in a Typescript Angular controller fails to run

Once the following line of code is executed cockpit.controller('shell', shellCtrl); within my primary module, the shell controller gets registered with the Angular application's _invokeQueue. However, for some reason, the code inside t ...

Enable the experimentalDecorators option in atom-typescript to utilize decorator syntax in your

I recently started using the Atom editor alongside the atom-typescript package for an ongoing project, and I keep encountering this warning message. There is experimental support for decorators that may change in upcoming releases. To remove this warnin ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...