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

Does v-if cause the jquery clock picker to malfunction?

Here is my unique div where the clockpicker library functions correctly. <div class="input-group clockpicker"> <input type="text" class="form-control" value="18:00"> <span class="input-group-addon"> <span class ...

Problem encountered in a simple Jest unit test - Unexpected identifier: _Object$defineProperty from babel-runtime

Struggling with a basic initial test in enzyme and Jest during unit testing. The "renders without crashing" test is failing, as depicted here: https://i.stack.imgur.com/5LvSG.png Tried various solutions like: "exclude": "/node_modules/" in tsconfig "t ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

What could be causing Vuejs to not update elements promptly?

Currently, I am encountering a scenario where I am adding options to a select element using Vue.js when the @change event of that specific element is triggered. An issue arises where the new option is not 'registered' until I exit the function. ...

Tips for including new items in an array within a subscribe valueChanges in Angular

What is the process for extracting values from a reactive form and storing them in an array when the form is valid? My application features dynamic forms with various fields that appear dynamically. retrieveFormValues(){ let valuesArray = []; this.fo ...

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

The video does not begin playing automatically after utilizing react-snap

I included a background video in my react app that auto-plays upon page load and functions perfectly. Here is the JSX code I used: <video autoPlay loop style={{ backgroundImage: `url(${topVideoImage})`, }} muted playsInl ...

Is it possible to create a TypeScript class that contains various custom functions?

Exploring TypeScript is a fresh yet exciting journey for me! In the world of JavaScript, checking if an object has a function and then calling it can be achieved with code like this: if(this['my_func']) { this['my_func'](); } Howeve ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

Troubleshooting GLSL scripts within a web-based WebGL environment

Are there ways to debug GLSL code or display variable values directly from within the GLSL code when using it with WebGL? Does three.js or scene.js offer any features for this purpose? ...

Encountered an error while attempting to log in: TypeError: the property 'id' of null cannot be read

I am facing an issue with the login process, specifically getting a TypeError: Cannot read property 'id' of null error message. How can I debug and resolve this error? var cas = require('cas-client'); get_forward_url(function(forwardur ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

Is there a way to ensure that fields in a sub component are validated whenever we attempt to switch the Tab using a route

Hi there, I could really use your assistance. I've done some research, but I haven't been able to find a suitable solution for my problem. I have this shared component that contains the following code which enables tab navigation through various ...

Is it possible to selectively mock certain components of an external module using jest?

I am totally new to using Jest, especially in regards to unit tests, and I am struggling to write a test for a specific scenario. I know that you can mock an external module like this.. jest.mock('@organisation/library', () => ({ Database: j ...

Add some texture to one side of the quadrilateral

I have a project in threejs where I need to display an image of a cat within a rectangle. The challenge is to render the right half of the rectangle in red, while displaying the full stretched image of the cat on the left half. Here's my current scen ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

Unusual behavior of Typescript with Storybook's addon-docs

I'm trying to integrate storybook addon-docs into my TypeScript React project. Everything seems to be almost working, but I've noticed that the file name is affecting how the props type table gets rendered. Here is my file structure: src - Butto ...

Utilizing data as a substitute when creating a SearchBar using Vue3

My VueJs3 application has a search bar implemented using .filter(), and it seems to be working fine. However, when I try to pass the value from my methods to the template, an error occurs. My data becomes a proxy and I am unable to use it in that format. ...

Using POST parameters with HTTP Client in Angular 2

I have been working on converting my jQuery code into Angular2. While the jQuery code is functioning correctly, the Angular2 code seems to be producing a different output from the API. I have already compared the parameters and endpoint using firebug/cons ...