Is there a way to prevent nesting subscriptions in rxjs?

Currently, I am working with a code that contains nested subscribes:

.subscribe((data) => {
  const { game, prizes } = data;
  this.ticketService.setListOfTickets(game.tickets);
  this.ticketService.getListOfTickets()
    .subscribe((data: any) => {
      this.listOfTickets = data;
    });
  this.game = game;
  this.type = game.type;
  this.combinations = prizes.map((el: Prize) => el.patterns).flat();
});

Is there a way to restructure this code in order to eliminate the need for nested subscriptions?

Answer №1

.pipe(
    switchMap(response => {
      this.ticketService.updateTicketsList(response.game.tickets);
      return this.ticketService.getAllTickets().pipe(
        map(updatedTickets => ({ ...response, updatedTickets }))
      );
    })
)
.subscribe(({ game, prizes, updatedTickets }) => {
    this.updatedTickets = updatedTickets;
    this.game = game;
    this.type = game.type;
    this.combinations = prizes.map((item: Prize) => item.patterns).flat();
});

In the code snippet above, switchMap function transforms the result of the initial request and switches to a new observable.

Answer №2

To consolidate multiple API calls into a single subscription, you can utilize forkJoin method. Without seeing the actual function name in your code, I'll refer to it as: gameService.getGames()

forkJoin([this.gameService.getGames(), this.ticketService.getListOfTickets()]).subscribe((data) => {
        const { game, prizes } = data[0];
        this.ticketService.setListOfTickets(game.tickets);
        this.listOfTickets = data[1];
        this.game = game;
        this.type = game.type;
        this.combinations = prizes.map((el: Prize) => el.patterns).flat();
      });

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

What is the best way to invoke a function in Typescript while retrieving data?

Is it possible to run a query in my main.ts file with another ts file and then pull the result of the query into another file? If so, how can this be achieved? Here is an example from my main.ts file: async function getAllTips() { const tips: any = []; ...

Setting dynamic values for SASS mixins in Angular 2 with Ionic 2

In my SCSS file, I have created a mixin to generate a progress bar. @mixin progressBarMix($name, $size, $perc, $color, $colorBack) { .progressBarWrapper { &#{$name} { $sizeFill: $size / 100 * $perc; .progressBarEndFilled { b ...

Utilizing the ternary operator in Angular HTML templates

Using the ternary operator in HTML can simplify your code: <div> {{ showStringOneFlag ? 'Display String 1' : 'Display String 2' }} </div> This approach could save you from setting a string variable multiple times in JavaSc ...

When using Google Maps, be sure to load it carefully as it may appear gray on the second attempt

After developing an Ionic 2 / Angular 2 App with integrated Google Maps, I encountered a problem. The second time the Google Maps loaded, it appeared completely gray. Despite trying various solutions found online such as triggering 'resize' event ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

How to dynamically load a component in Angular 5 and open a sidenav

Hey there! I recently created this project on StackBlitz check it out here! I'm looking for ways to dynamically load components inside a sidenav. For example, from the NavigatoComponent, I want to open the sidenav on click with the Acomponent load ...

Stop users from switching to other tabs within mat-tab-group without using ViewChild

I am working with a mat-tab-group component in Angular : mat-tab-group class="brand-tabs" [disableRipple]="true" *ngSwitchCase="types.project" (selectedTabChange)="changeProjectTab($event)" [selectedIndex]="selectedProjectIndex" > . ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

Is there any re-rendering optimization feature in Angular 2?

After experimenting with React for a few months, I've noticed that it doesn't just re-render a component entirely. Instead, it identifies the differences and updates only those parts. Does Angular 2 operate in a similar manner? Additionally, whe ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

A comprehensive guide to dynamically rendering components and implementing dynamic CSS in Angular 6

I successfully implemented a Directive, but I am now facing the challenge of adding CSS styling to it. I have experimented with array objects, however, I ended up applying CSS directly in the HTML. My goal is to create a single component where I can pass ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

Challenges surrounding asynchronous functionality in React hooks

I've been facing some issues with this code and have resorted to debugging it using console.log(). However, the results I'm getting are not making any sense. Can someone help me identify what's wrong with this code? I noticed that my console ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

Encounter an Unexpected Token Issue when using NextJS-auth0 in Jest

I am facing a problem with my Next.js app that is integrated with the nextjs-auth0 package. Whenever I attempt to test a particular file and include the following import: import { getSession } from '@auth0/nextjs-auth0'; An error occurs, stating ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Tailored validation for targeted field

How can I validate a partial form based on requirements? Built with Angular 7 and Clarity I have a form using the clrForm component that includes: Field 1: Name Field 2: URL Field 3: Date The form also has two buttons: Button 1: Verify Button 2: Su ...

Effortless method for combining PHP API with Angular 2 application on your computer

Currently, I am developing a new Angular 2 application that interacts with a REST API built on PHP. To simulate the data flow, I have generated mock data in a json file for the front end. The PHP REST API was created using MAMP and has been tested succes ...