Display the next page once two distinct service requests have been received

When I need to display a page after retrieving data from two different services, service1 and service2, how can I achieve this without nesting the second service call inside the first one?

Instead of chaining the service calls, I want to make separate requests for each service. Here's an example:
this.service1.getProfile1(id).subscribe((data1) => {
  console.log(data1);
});
this.service2.getProfile2(id).subscribe((data2) => {
  console.log(data2);
});

How do I determine when I have received the data from both service calls?

Answer №1

If you're looking to combine multiple observables in RxJS, consider using forkJoin. Check out the documentation at this link.

import { forkJoin } from 'rxjs';

forkJoin(
  this.userService.getUserData(id), 
  this.postService.getPostData(id)
).subscribe(([userData, postData]) => {
  console.log(userData, postData);
});

Answer №2

To merge the two observables using a fork join, follow this example:

import { forkJoin } from 'rxjs';

    forkJoin([
      this.apiService.getData1(),
      this.userService.getData2(),
    ]).subscribe(response => {
      const result1 = response[0];
      const result2 = response[1];

      console.log(result1);
      console.log(result2);
    });

The requests are executed in sequence, and the observable produces an array of outcomes. The order in which the items are received corresponds to the order in which they were included in the forkJoin.

Answer №3

Within this specific scenario, your objective is to guide the user through a process involving two service calls to distinct endpoints. Upon receiving responses from these endpoints, you aim to merge them using fork join before passing them on to the component as an observable.

However, it seems that you are seeking a method to initiate the http calls prior to redirecting to the page in question. Angular router offers a suitable solution for this situation.

You have the option to designate which http calls should be executed even before the user reaches a certain page.

To achieve this, implement resolve at the service level and include that service within the route resolve function.

For example :

import { Injectable } from '@angular/core';
import { APIService } from './api.service';

import { Resolve } from '@angular/router';

import { ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve<any> {
  constructor(private apiService: APIService) {}

  resolve(route: ActivatedRouteSnapshot) {
    return this.apiService.getItems(route.params.date);
  }
}

Routes :

{ path: 'items/:date', component: ItemsComponent, resolve: { items: APIResolver } }

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 mat-select value is experiencing issues when including spaces and is not functioning as

There seems to be a minor mistake that I can't seem to locate. Below is the form in question: <mat-card> <form #f="ngForm"> <mat-card-content> <mat-form-field> <mat-select [ngModel]="data.variab ...

Traditional method for comparing prevProps in componentDidUpdate

As I work on prototyping, I've noticed that when new props come in as an array of complex objects, prevProps.myProp===this.props.myProp always returns false. While using JSON.stringify for comparison seems to work, it doesn't feel very reliable. ...

Dealing with the issue of asynchronous operations in a controller using async/await function

Something strange is happening here, even though I'm using async await: const Employee = require('../models/employee'); const employeeCtrl = {}; employeeCtrl.getEmployees = async (req, res) => { const employees = await Employee.find( ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'. JavaScr ...

Issue with Ckeditor inside a bootstrap modal

I am encountering an issue while trying to integrate ckeditor into a bootstrap modal. Whenever I attempt to use it, the functionality does not work as expected. Clicking on any icons triggers an error in the console stating Uncaught TypeError: Cannot rea ...

Querying MongoDB to locate books by the same author or those that are categorized in at least one similar category

Looking to discover books by the same author or with at least one matching category. This is how my Book Schema looks: const bookSchema = new Schema( { title: { type: String, required: true }, author:{ ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

During the execution of Jest tests, a singular module is experiencing undefined imports

Encountering an unusual issue with Jest, create-react-app, and typescript. Out of the blue, Jest has stopped importing my "./ProcessStore" module correctly. This module is a dependency of something that is being imported in my tests. The error message in ...

Retrieve: proper authentication credentials were not provided

Whenever I make a request, everything works fine and I receive the data: const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console. ...

Using ngFor and click function in Ionic and Angular

Recently, I delved into the world of Ionic and started working on an app that features a unique 'dictionary' functionality. The app allows users to press a button to hear either an English or German translation of a Dutch word through an audio fi ...

Determine the generic type of the parent class based on the constructor of the child class

Below is a code snippet illustrating the issue at hand: class Parent<T = unknown> { constructor(private prop: T) {} getProp(): T { return this.prop; } } class Child extends Parent { constructor() { super({ ...

Avoid re-rendering the page in Nuxt when adjusting dynamic parameters

My page has two dynamic parameters that trigger the fetch method to run again when the URL params are changed. I want to avoid this behavior. Fetch Method: async fetch() { await this.getFlightResult(); } Get Result Method: async getResult() { th ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...

Unexpected behavior encountered with RxJs Subject.subscribe function

When calling the Subject.subscribe method, an error is output as follows: TypeError: Cannot read property '_subscribe' of undefined at BidirectionalSubject._subscribe (Rx.js:10239) at BidirectionalSubject._subscribe (Rx.js:10239) at Bidirection ...

Searching for a four-digit number within a string using NodeJS Regex, alongside specific keywords

I have a regex pattern that should match strings with a specific year format. The template is 'Year--"high OR low"-level'. Here is the regex I've created: /Year-\d{4}-\b(low|high)\b-level/gi; When I test it using online regex ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

Attitude: Defiant and Ignoring Authority

So far, no suggestions have been made, indicating that maybe I haven't properly summarized the issue; The problem arises when I absolutely position the section with the class="container" using an additional class or id specific to that <div>. I ...

Vuetify input with appended button showing loader malfunction

One of the fields in my form is an email input with complex validation rules. I'm using Vuelidate for form validation, and once the user enters a valid email, I want to display a 'Check' button to verify if the user exists. While the server ...