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

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...

Is the presence of a potential leak suggested by this arrangement in the heap snapshot retainer hierarchy

While analyzing a Heap snapshot, I came across a retainer hierarchy that looks like this: Is it possible that the MuiThemeProviderOld element (highlighted in yellow and from the @material-ui/core library) is causing a memory leak for my gui instance as sh ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Attempting to Retrieve Information from a Get Request using Axios

I am attempting to retrieve SQL data from a GET request using axios. My backend is set up with an express server, and the front end is built with React. In my React component, I have a function that contains the axios GET call, which I then invoke within t ...

The button I have controls two spans with distinct identifiers

When I press the player 1 button, it changes the score for both players. I also attempted to target p2display with querySelector("#p2Display"), but it seems to be recognized as a nodeList rather than an element. var p1button = document.querySelector("# ...

Do Prisma Migrations Require a Default Value?

I'm struggling with Prisma data modeling and have tried almost everything to resolve an error I keep getting. The error states that the table needs a default value even though I have already assigned it an ID. I attempted to remove the relation name, ...

Presenting SQL information in a hierarchical Angular grid for easy visualization

As a newcomer to Angular, I have a requirement to display data in a multilevel/hierarchical Angular Grid. The data is retrieved from a SQL Database using a query with arguments provided in the where clause. Some questions that come to mind are: Is there ...

The jQuery hover function is not functioning properly on page load in Firefox

While this code is functioning smoothly in Chrome and IE, it seems to be encountering issues in Firefox! <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> JS: $(window).load(function(){ $("#bosti ...

ParcelJS takes a unique approach by not bundling imported JavaScript libraries

My NodeJS app, which is a Cloudflare Worker, seems to be having trouble with bundling the 'ping-monitor' dependency. In my main typescript file (index.ts), I import the handler module and the first line reads: const Monitor = import('ping-m ...

Issues with Angular ChartJS where the minimum value for scales and callback functions are not functioning as

I am encountering an issue while using ChartJS line chart in my Angular 9 application. I am attempting to adjust the Y axes of my chart so that they start from 0 (instead of the minimum value) and include a '%' symbol after each value. Below is a ...

Creating a new library that relies on Ionic 2 and Angular 2 with Dependency Injection

Let me set the stage for our current dilemma: Within my team, we are in the process of developing an Ionic 2 application that comes in various customer-specific versions. Despite sharing similar functionalities, these versions differ in settings, names, a ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Is there a more efficient way to consolidate multiple functions like this into one cohesive function instead of having to define each one separately?

After attempting to implement a loop without success, I also considered using regex but that did not work either. The code in question is part of a larger project that involves dynamically adding and deleting fields using jQuery. The classes and ids used f ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

Using Angular 2 to showcase icons in the navbar post authentication

The structure of my components is as follows: The app component contains a navigation bar and router outlet. The navigation bar includes a logo, generic links, and specific links that are only shown after user login and authentication. The router outlet de ...

Is there a way to programmatically simulate clicking on the "Cancel search" button?

I have a text input field with type "search". In order to perform UI testing, I need to simulate clicking on the "cancel search" button: The code for this specific input field is as follows: <input type="search" value="user"> Although the cancel b ...

The choice between using "npm install" and "npm install -g" for

New to the world of node, and feeling a bit lost when it comes to all this "install" stuff. Could someone clarify for me, what sets apart install from install -g? If something is installed with install -g, can it be accessed from anywhere, or is it restr ...

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

How to Send an Array to AJAX and Retrieve the Data in Codeigniter Controller

I am attempting to retrieve table data, store it in an array, and pass it to the controller so I can write it in PHP Excel. Previously, I had success with other data but now my excel file is turning up empty. Below is the JavaScript code snippet: var Ta ...