Tips for managing numerous HTTP requests in Angular 6

I have a method that is trying to chain together 3 requests like this:

showProfileDetails() {
  this.getUserInfo(this.currentUser.id).pipe(
    mergeMap(e =>
      this.getAccounts(this.currentUser.id)
    ),
    mergeMap(e =>
      this.getPayments(this.currentUser.id)
    )
  ).subscribe(data =>
    console.log('first attempt on observables: ', data)
  )
}

My goal is to fetch the data from each call sequentially, store it in a variable, and then display it on the web page. However, I am only getting the data from the last call, which also happens to return an error. How can I handle this error without interrupting the process? Thank you for your help, as I am new to Angular.

Answer №1

If you want to efficiently handle multiple HTTP requests, consider using forkJoin in RxJs:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/forkJoin';

fetchData(): Observable<any> {
  const userData = this.http.get(USER_ENDPOINT).map(res => res.json());
  const accountData = this.http.get(ACCOUNT_ENDPOINT).map(res => res.json());
  const paymentData = this.http.get(PAYMENT_ENDPOINT).map(res => res.json());

  return Observable.forkJoin([userData, accountData, paymentData])
     .map(data => {
        // data[0] => user
        // data[1] => account
        // data[2] => payment
     });
}

Answer №2

Here's a StackBlitz I created for you to check out:

https://stackblitz.com/edit/angular-async-calls-httpclient

{View in Full Page}

The following files are worth checking:

  • services > http.service.ts {contains the method for making GET requests}
  • services > users.service.ts {contains other methods}
  • app.component.ts

In the app.component.ts file, within the ngOnInit function, there are asynchronous calls that assign values to variables, which can be logged or used in templates.

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

Is it possible to refresh the JSViews data that is underneath using an onclick event?

I have created a photo gallery using a JSViews template which includes upvote and downvote buttons. When these buttons are clicked, it triggers a database update to increase the score. However, I am facing an issue with updating the Score field in the HTML ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Angular Ahead-of-Time (AOT) compilation causes multiple route definitions to be

Having a bit of trouble configuring ahead-of-time compilation for my lazy-loaded Angular app. The lazy-loaded routes are specified in the app.routes.ts file, which is imported by app.module.ts. Running ngc results in the content of app.routes.ts being mer ...

Utilize Quasar CSS breakpoints within Vue expressions for responsive design

I am currently using the QDialog component from Quasar Framework and I want to set the value of the maximized property based on the current screen size, specifically being maximized for small screens only. Is there a way for me to reference a variable in ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

What is the process for sending a request to Electron from my backend using NAPI?

I'm currently working on a project using Electron, and I have a NAPI file that contains my backend code. In my user interface, when a specific button is clicked, it triggers a function that calls the function from NAPI. Electron acts as the bridge bet ...

Oops! Looks like we encountered a problem: "Uncaught ReferenceError: process is not

As I work on my project utilizing angular 6 with Spring-boot, I have encountered an error that I am struggling to resolve. Specifically, the error message reads: Uncaught ReferenceError: process is not defined at Object../node_modules/util/util.js (ut ...

Learn how to incorporate additional rows into a table by pressing the plus button within the table with the help of Angular

I require some assistance. I am looking to dynamically generate a row after clicking on the plus button using angular.js. The newly created row should contain an ID and model generated dynamically. Here is an overview of my code: <table class="table ta ...

Show information upon opening

I am currently working on a project that involves 4 different divs, and I need the content of each div to be displayed based on dropdown selection. I found a code snippet that was close to what I needed, but after trying to adjust it, I haven't been a ...

Resolve the issue of autofill data overlapping with field labels

My form incorporates the Canada Post AddressComplete tool, which functions similarly to Google Maps Autocomplete. As you type your address, suggestions appear in a drop-down menu. However, after selecting an address, the text in the Postal Code and City f ...

Exploring nested components traversal in React

In my project, I have created a product component that displays the products' name, price, and description. const Product = (props) =>{ return( <div> <p>Price: {props.price} </p> <p>Name: ...

Angular service designed for distributing a collection of data across nested levels

How can values be effectively shared across components within a specific hierarchy without having to pass them down individually, especially when some nodes require the values and others do not? It can become messy. I've been considering something li ...

Differences Between DOM and Refs in React

When it comes to React, what distinguishes the use of DOM from Refs? While it is possible to utilize typical JavaScript DOM node selectors in React for targeting specific elements, refs also offer a way to achieve the same functionality. What are the adv ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Remove click event listeners from a specific element within a group of selected elements using D3

In my D3 class, I have a group of selectors that I want to remove the click event from: d3.selectAll('.selectors').on('click',function(){ //Remove the click event from the currently clicked element. }); I'm encountering tw ...

I am having difficulty retrieving the user's IP address in VueJs

Here is the code snippet: Vue.mixin(windowMixin) export default { name: "App", methods: { getIpAddress(){ localStorage.getItem('ipAddress') ? '' : localStorage.setItem('ipAddress&apos ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...

Essential parameters needed in a Typescript function signature

My code includes the following type definition: type FuncWithRequiredParams = (a: number, b: number, c:string) => void const func1: FuncWithRequiredParams = (a: number, b: number, c: string) => {} // This is functional const func2: FuncWithRequiredP ...

Obtaining the value of SCOPE_IDENTITY to be used in an Angular application

Having trouble getting the ID of the newly inserted table row to use in my Angular application. Any suggestions on how to pass it while posting? Can't quite figure it out. public string Post(Profile profile) { try { string ...