Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError block, I'm struggling to retrieve the response in the switchMap method of the first call. What could be wrong with this implementation in the given scenario? How can I access the response from the first request and then proceed with or skip the second call based on this initial response?

let result;
let statusCode;

this.demoService.create(...).pipe(
    catchError((err: any) => { ... }),
    switchMap(response => {

    // Need to access the response of the first request here
    statusCode = response.statusCode;

    if(...){
        return this.demoService.update(...).pipe(
            catchError((err: any) => { ... }),
            map(response => {
            return {
                result: response
              }
          }
        )
      )}
    }
  ))
  .subscribe(result => console.log(result));

Answer №1

The inquiry still seems unclear to me. I will provide a more general response to elucidate a few points.

There are several key aspects to consider:

  1. When an observable emits an error notification, the observable is deemed closed (unless reactivated) and subsequent operators dependent on next notifications will not be triggered. To handle error notifications within the context of switchMap, you can return a next notification from the catchError using something like

    catchError(error => of(error))
    with RxJS of. This way, the notification will be intercepted by the following switchMap.

  2. You must always return an observable from switchMap regardless of conditions. In instances where you do not want to return anything upon condition failure, you can use RxJS NEVER. Alternatively, if you wish to emit a message caught by the subscriptions' next callback, you can utilize RxJS of. Replace return NEVER with

    return of('Some message to be emitted in the subscription's next callback');

import { of, NEVER } from 'rxjs';
import { switchMap, catchError, map } from 'rxjs/operators';

this.demoService.create(...).pipe(
  catchError((err: any) => { ... }),
  switchMap(response => {
    statusCode = response.statusCode;

    if (someCondition) {
      return this.demoService.update(...).pipe(  
        catchError((err: any) => { ... }),
        map(response => ({ result: response }))
      );
    }
    // Display error message
    return NEVER;               
  }
)).subscribe({
  next: result => console.log(result),
  error: error => console.log(error)
});

Answer №2

You have the option to utilize the iif method for implementation.

this.demoService
   .create(...)
   .pipe(
     // Utilize tap first to confirm existence of a response for processing
     tap(console.log),

     // The iif method allows for conditions such as "response.user.exists"
     // If true, execute the update$ observable; otherwise, run the default$
     // Note: All must be observables due to being inside switchMap
     switchMap(response => 
      iif(() => 
        response.user.exists, 
        this.demoService.update(response.id),    // Provide ID parameter
        of('Default Random Message')
      )
     ),
     catchError((err: any) => { ... })
   );

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

"Struggling with a basic Javascript function to refresh parts of a web page by calling a .php

After spending several hours browsing the internet, I am still struggling to get this straightforward example to function properly. Could someone please lend me a hand? My goal is to use JavaScript to display the contents of a PHP file. The display should ...

Using TypeScript's `async await` within a nested function invocation

I am having trouble extracting the 'assigned suspect' from the callbacks, as it is showing up as undefined. Strangely, it works fine within an if statement. I believe the issue is related to the await/async functionality. Any assistance would be ...

Dropdown menu not populating with options in AngularJS ngOptions

It's puzzling to me why the dropdown menu is not being populated by ng-options. Despite JSON data being returned from the service and successfully logged in the controller, ng-options seems to be failing at its task. <tr class="info"> <td ...

A comprehensive guide to leveraging synchronous execution of setTimeout in JavaScript

Can the desired output shown below be obtained using setTimout? If it is possible, please provide your insight: console.log("1st"); setTimeout(() => { console.log("2nd"); },0); console.log("3rd"); The expected output should be: 1st 2nd 3rd ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

The MUI component received props that were not defined

I created a customized MUI card with the intention of applying a dark background when the darkBg prop is passed. However, I've encountered an issue where despite passing darkBg as true, the card's background remains white. To troubleshoot, I atte ...

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

Encountering an internal/modules/cjs/loader.js:892 error when attempting to install the newest version of node.js on Windows 10

After recently updating my node.js to the latest version using chocolatey, I encountered a problem with my command prompt displaying the following error: internal/modules/cjs/loader.js:892 throw err; ^ Error: Cannot find module 'C:\Users&bso ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

Can child directives in Angular 2 harness the power of parent providers?

I am facing an issue while trying to utilize a service as a provider for general use in a Directive rather than a Component. The problem arises when the service is not being received in the child Directive, despite my expectation to use it within the direc ...

Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here $(document).ready(f ...

What is the best way to include a router-link in a button click event in Angular 8?

Can someone please help me with adding a routing function to a button in Angular? I have already included a (click) function on the button, but how do I actually make the function navigate within the home.ts component? <button class="navbut" (click)= ...

How can animations be disabled in Angular/Javascript?

I have been assigned the task of developing an Angular component for my company's applications that will include a toggle to disable all animations within the app for accessibility purposes. It is important to note that I am unable to go into each in ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

Guide to customizing the default scrollbar colors in Nextjs

When browsing websites like tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox, you may have noticed that they utilize the default scrollbar style but allow users to change its colors through a dark/light mode button. The appearance of ...

Can a person select a characteristic like "height" using Javascript?

Is it doable to set a height for an image in CSS, then detect this gradient using JS and double the width based on the height x2.25? Could this be achieved? ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Display current weather conditions with the Open Weather API (featuring weather icons)

Hello everyone, I need some help from the community. I am currently working on a weather app using the openweather API. However, I'm facing an issue with displaying the weather conditions icon for each city. I have stored every icon id in a new array ...

I am facing an issue with updating the mat-table after pushing values to a

I have a uniqueFormGroup with UniqueFormArray and a special-table that displays the array. When I add new uniqueFormGroup to UniqueFormArray, the special-table doesn't add new row. I was attempting to implement trackBy, but I am unsure of where (and ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...