Utilizing nested observables for advanced data handling

Consider the following method:

public login(data:any): Observable<any> {
  this.http.get('https://api.myapp.com/csrf-cookie').subscribe(() => {
    return this.http.post('https://api.myapp.com/login', data);
  });
}

I want to modify it so that the nested observable is returned, allowing the calling code to be structured as follows:

this.apiService.login(credentials).subscribe(() => {
    // redirect user to their dashboard
});

The goal is for the inner HTTP request to wait for the outer one to complete and be included in the return value of the method. Currently, the above implementation does not achieve this.

Answer №1

it's recommended to utilize the switchMap method, you can refer to the documentation on switch map

public logIn(data:any): Observable<any> {
  return this.http.get('https://api.myapp.com/csrf-cookie').pipe(
    switchMap(x => this.http.post('https://api.myapp.com/login', data))
  );
}

avoiding nested subscribes with rxjs is typically advised. There are plenty of useful operators in the library that can help accomplish tasks without nesting. In scenarios like the one mentioned above where one call relies on another, switchMap(...) is the optimal choice.

The code has also been updated to return the observable rather than the subscription

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

The script for tracking cursor coordinates is incompatible with other JavaScript code

<html> <script language="javascript"> document.onmousemove=function(evt) { evt = (evt || event); document.getElementById('x').value = evt.clientX; document.getElementById('y').value = evt.clientY; document.ge ...

Steps for placing a second pie chart alongside the initial one within a Bootstrap card

Is it possible to have two pie charts with different values using chart.js? I attempted to duplicate the script for the first chart to create a second one, but it did not display correctly. Why is the second pie chart not showing up? $(document).ready(fu ...

Experiencing challenges with showcasing numerical values in the grid cells

My latest project involves creating an interactive sudoku solver. I've successfully created a grid made up of various elements to resemble an empty sudoku grid. However, my challenge lies in getting the numbers to display within the grid cells. Click ...

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

When a directive is passed a string with HTML tags, the tags are not displayed/rendered as expected

When it comes to passing a string with HTML content to my Angular directive, I've encountered an issue where the rendered output treats the HTML as text. While researching possible solutions, most of them seem to rely on using ng-bind-html directive, ...

Show notifications after being redirected to a new page

My goal is to submit a form and have the page redirected to a different URL upon submission. Currently, everything works as expected, but there is an issue with the timing of the toast message. The toast message appears immediately after the user clicks th ...

Having trouble storing data accurately in local storage using React

I implemented a combination of useContext and useEffect to store useContext data in local storage, but I am facing challenges due to conditional rendering. The scenario involves displaying a sign-in button when the user is not logged in and a log-out butto ...

development of MapLayers with rails and javascript

As a newcomer to RoR, I am encountering an issue that seems to be eluding me. I attempted to replicate the example application found on the mapLayers GitHub repository at https://github.com/pka/map_layers/wiki. However, all I see is the JavaScript code gen ...

Is there any benefit to fetching data in `{#await}` or `onMount` instead of `load` in SvelteKit, especially considering the impact on `+server`?

keyword: displaying loading spinner Imagine accessing a route like /dashboard, where most of the page content remains constant but certain sub-components require real-time data. If I retrieve this data within a load function, the entire route will remain ...

Using jQuery to target nested HTML elements is a great way to efficiently manipulate

Within the code below, I have a complex HTML structure that is simplified: <div id="firstdiv" class="container"> <ul> <li id="4"> <a title="ID:4">Tree</a> <ul> <li id="005"> ...

Put dashes in the middle of each MongoDB post title

In my express app, users can create and view posts. Currently, I search for posts by their title. However, I am encountering an issue when the post title contains spaces. The search function works perfectly for titles without spaces, but it gives an error ...

The sidebar vanishes when you move your cursor over the text contained within

My issue is that the side menu keeps closing when I hover over the text inside it. The "About" text functions correctly, but the other three don't seem to work as intended. Despite trying various solutions, I am unable to identify the root cause of th ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

How can I modify the # symbol with .htaccess?

When someone accesses the following URL: www.facebook.com/index.php#sk=inbox The .htaccess file will redirect it to the server as: www.facebook.com/index.php?sk=inbox This allows me to retrieve the value of sk using PHP like this: *echo $_GET[&a ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

Ensure UseEffect is only triggered once with specific dependencies

Whenever the component is loaded, I have a method called useEffect() that runs once. useEffect(() => { (async function fetchData() { const results = await stateIsoAPI(); setStates(results); // API results to trigger other Use effect ...

Illuminated Box with Text Beneath Image Overlay

Is there a way to customize the text displayed under each zoomed-in image even further, using images, etc. instead of just relying on the alt text? An ideal solution would involve displaying the text in a div. You can find the codepen here: // Looking ...

Is it possible to load a script conditionally in Angular 2 using the Angular CLI

Is it possible to conditionally load scripts using Angular CLI? I am looking to dynamically load a script in this file based on the environment or a variable. For example, I want to load a specific script in production but not in development. How can I ac ...

Designing the Pull to Refresh feature in Nativescript Angular

I've been experimenting with the Nativescript Angular Pull to Refresh Styling demo (Link) and I'm running into an issue where this.myListViewComponent remains undefined, causing the following snippet not to trigger: if (this.myListViewComponent ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...