Angular: Using ngrx for Nested HTTP Calls

Looking at my Angular code, I am trying to figure out how to convert nested HTTP calls into the ngrx pattern. My idea is to create separate actions for getUser and getPost, but I am struggling with passing the getUser response as a parameter to the getPost function...

ngOnInit() {
  this.http.get('localhost:8080/api/user').subscribe(user => {
    let headers = new HttpHeaders({
      'userId': user.id
    });

    this.http.get('localhost:8080/api/posts', {
      headers
    }).subscribe(posts =>
      this.posts = posts;
    )
  })
}

Answer №1

Implementing higher order operators like concatMap, switchMap, exhaustMap, and mergeMap can enhance the functionality of your code. An example transformation could be seen below:

ngOnInit() {  
  this.http.get('localhost:8080/api/user').pipe(
    mergeMap(({id: userId}) => {
      const headers = new HttpHeaders({
        'userId' : user.id
      });
      return this.http.get('localhost:8080/api/posts', {headers})
    })
  ).subscribe(post => this.posts = post)
}

If you have the ability to modify the backend, it is recommended to update your api to posts/:id instead of passing it as a header. This can be achieved as shown below:


ngOnInit() {  
  this.http.get('localhost:8080/api/user').pipe(
    mergeMap(({id: userId}) => this.http.get(`localhost:8080/api/posts/${userId}`)
  ).subscribe(post => this.posts = post)
}

Additionally, integrating async pipes can simplify your code and handle subscriptions automatically, making maintenance easier. Here's how you can update your TS file and html:

In your TS file

user$ = this.http.get('localhost:8080/api/user');
posts$ = this.user$.pipe(
  mergeMap(({id: userId}) => this.http.get(`localhost:8080/api/posts/${userId}`)
)

and in your html

<div *ngFor='let post of posts$ | async'>
  <!-- post variable accessible here -->
</div>

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 component is unable to access the injected service from a separate module due to its null

In my Angular v6 project, there are 2 modules: app.module.ts, which includes the AppComponent and BoatComponent, and imports another module called draggable.module.ts. app.module.ts @NgModule({ declarations: [ AppComponent, BoatComponent ...

Encountering a problem: array property length not found in Angular application?

I am trying to create a list of superheroes by looping through an array, but I keep encountering an error stating that the property length is missing from the array. (please refer to the screenshot) Here is my code in app.component.ts import { Component ...

Having trouble navigating to a child page in Angular 4

When I try to follow the Angular routing & navigation example, I encounter an issue where my page displays as "file not found" when I route. Even when I navigate to the profile page at profile.component.html, I can see my columns, but nothing appears from ...

Error encountered when using Angular Material date-time picker

I encountered an error in the console when trying to use the Angular Material datetime picker. Although it functions correctly, my tests failed due to this error. https://www.npmjs.com/package/@angular-material-components/datetime-picker <mat-form-fiel ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

The Angular overlay is concealed beneath the pinned header

I am seeking a solution to have a mat-spinner displayed on top of my app while it is in the loading state. Currently, I am using an overlay component with Overlay from @angular/cdk/overlay. The issue arises when part of the spinner that should be overlai ...

Step-by-step guide on incorporating HTML into a popover within Angular4

After successfully implementing a hover popover in Angular using PopoverModule from ngx-popover, I now need to modify the content inside the popover. My search led me to this example: <ng-template #popContent>Hello, <b& ...

What is the best way to showcase a collection of inherited objects in Angular?

How can I efficiently display a list of various objects that inherit from the same abstract class in an Angular application? What is considered optimal practice for accomplishing this task? Consider the following basic model: abstract class Vehicle { ...

Angular 2 Form Error: Control Not Found

I'm facing an issue with Angular 2 Forms where adding more than one control seems to be getting ignored. Despite following numerous guides on how to properly implement this, none of the suggested methods seem to work in my case. In my template, I hav ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Display the specified [object][object] in the header of Angular PrimeNG Multiselect component

When using angular primeng multiselect, it sometimes displays [object][object] in the header instead of the optional label when in edit/on focus state. Here is my code snippet <p-multiSelect(onFocus)="insertOptions(row,itemProperty.options,itemPropert ...

Disappearance of Current User in Console When Refreshing Angular 4/5 Firebase

After creating an Angular 5 login using Firebase, I noticed an issue with the authentication object disappearing upon page reload. Even though the user remains logged in, the auth object vanishes once the page is refreshed (the username is still displayed ...

What is the best way to configure the default entry point for a package.json file in a React

I'm having trouble with the default export in my package.json file. when I try to import: import { Component } from 'packagename/'; // size 22kb or import { Component } from 'packagename/dist' // size 22kb; but import { Component ...

Implementing a boolean toggle method in Typescript for a class property

Hello there, fellow programmers! I am interested in changing the value of a class field using a method. I have a button in Angular that, when clicked, triggers the onSave() method: export class CourseComponent { isActive:boolean; onSave() { ...

Why does Angular keep changing my request method to OPTIONS?

I've been working on setting up a JWT Interceptor in Angular. Following the example provided here, I implemented my JWT interceptor using the code snippet below: import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler, HttpHeaders } from &apos ...

Attempting to establish a connection with Redis through the combination of TypeScript and Node.js

Currently, I am attempting to establish a connection with Redis using TypeScript and Node.js. However, I am encountering an issue where **error TS2693: 'RedisStore' is designated as a type but is being utilized as a value in this context.** let r ...

How to make Angular 5 wait for promises to finish executing in a for loop

My task involves working with an array like this: arr = ['res1', 'res2', 'res3']; For each value in the arr, I need to make an API call that returns a promise. arr.forEach(val => this.getPromise(val)); The getPromise me ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

Is there a new implementation of "ComponentFactoryResolver deprecated" with missing attributes?

Since Angular 13, the usage of ComponentFactoryResolver has been deprecated. Finding a suitable replacement is proving to be a challenge as the old rootSelectorOrNode parameter is no longer available in the new solution. I have a requirement to dynamicall ...