A guide on leveraging rxjs for handling multiple inner nested subscriptions

I have a code snippet where I have nested subscribe functions, and while it works, the structure is not ideal. I am looking to refactor this code using rxjs (forkjoin or mergemap) but I am unsure how to do so. Any assistance in helping me optimize this would be greatly appreciated.

this.chapservice.cycle().subscribe((current) => {
      this.selectedCycleId = current.ratingCycleId;
      this.chapService
        .getChapterEvalWithSkills(
          this.activeUser.ipn,
          this.selectedRatingCycleId
        )
        .subscribe((response) => {
          console.log("response", response);
          if (response && response.length > 0) {
            this.chapterEvals = response;
          }
        });
      this.chapservice
        .getIsitEmployeeStatus(this.activeUser.ipn, this.selectedCycleId)
        .subscribe((sdpStatus) => {
          this.activeUserStatus = sdpStatus;
       if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
                 //do something
            }
        });
    });

Answer №1

To achieve the desired outcome, it is recommended to combine the use of forkJoin and switchMap.

  • Why choose switchMap? - This operator is suitable when there are dependent values that require sequential execution.
  • When to opt for forkJoin? - In this scenario, you have the option to utilize either forkJoin or mergeMap.

Implementation:

this.chapservice.cycle().pipe(
  switchMap((current: any) => 
     forkJoin(
        this.chapService.getChapterEvalWithSkills(
           this.activeUser.ipn,
           this.selectedRatingCycleId
        ),
        this.chapservice.getIsitEmployeeStatus(this.activeUser.ipn, current.ratingCycleId)
     )
  )
).subscribe(([chapterEvals, sdpStatus]) => {
      console.log(chapterEvals, sdpStatus);
      if (chapterEvals && chapterEvals.length > 0) {
        this.chapterEvals = chapterEvals;
      }
      this.activeUserStatus = sdpStatus;
      if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
             //perform specific action
        }
    });
});

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 selectpicker property is not recognized in the typescript file, as it does not exist within the IInstance

When attempting to create a group by multi-select dropdown with search functionality using Bootstrap-select, I encountered the following error message: "Property 'selectpicker' does not exist on type IInstance." Environment: Typescript 2.2 Angul ...

Tips for utilizing an observable in Angular without subscribing to it

I am currently working on an Angular 8 application that involves making API calls. Here is an example: getDossierEntry(patientUUID: string, type: String = ''): Observable<DossierEntry[]> { const entryType = type === '' ? ' ...

In Typescript, which kind of event is suitable for MouseEvent<HTMLDivElement>?

My goal is to close the modal when clicking outside the div element. Take a look at my code below. // The onClose function is a setState(false) function. import { useRef, useEffect } from 'hooks' import { MouseEvent } from 'react' imp ...

Unable to access the redux store directly outside of the component

When trying to access my store from a classic function outside the component, I encountered an error while calling getState(): Property 'getState' does not exist on type '(initialState: any) => any' Below is the declaration and im ...

Creating a PDF export of your grid using Kendo Grid is a straightforward

I've been facing a challenge while trying to export an entire page using Kendo Angular PDF. Everything works smoothly until I add a Kendo Angular Grid onto the page. The problem arises when certain rows go missing and extra blank space appears on some ...

Encountered an issue when trying to resolve module @angular/core while running the application

An issue occurred: Error in finding module @angular/core While working on my Ionic App, I encountered the error mentioned above. This is how my tsconfig file appears: "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": ". ...

"Receiving HTML response from an HTTP GET request in Angular 2

Attempting to transmit test data from my node.js server to the front end. router.get('/abc', (req, res) => { return res.json({ test: "success!" }); }); In my service component: private url = "http://localhost:4200/auth/abc"; getTitl ...

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .p ...

Bootstrap 4 navigation: The right side of the navigation bar

Currently working on designing a navbar in ng-bootstrap which involves Angular 4 and Bootstrap 4. The goal is to have some items aligned on the left as a pulldown menu, and other items on the right without any dropdown functionality. Progress has been made ...

Properly incorporating a git+https dependency

I'm facing an issue while trying to utilize a git+https dependency from Github to create a TypeScript library. I've minimized it to a single file for illustration purposes, but it still doesn't work. Interestingly, using a file dependency fu ...

Tips for looping through a Set in TypeScript

What is the best way to loop through a set in TypeScript? Using for..of does not seem to work properly: 'Set<string>' is neither an array nor a string type Using .forEach is not ideal since it obscures the context of this. I would rather ...

Using RxJS with Angular 2 to Split Observables in an Array

Looking for an API to return back an array and then split it into components for use with the "take" function of Observables. Currently working with Angular 2 / RxJS. This is my functioning code: public getFiltered(groupName:string, start?:number, num?: ...

Pushing items to an array is causing the loss of previously added data

Currently, I am working on developing a prototype of a Restaurants application using Angular 8. In this project, I have implemented @Input() to transfer individual restaurant data as an object from the parent component to the RestaurantCardComponent for pr ...

A new feature introduced in TypeScript, expression-level syntax was not present until it was added in JavaScript

Celebrating a Decade of TypeScript remarked that "It’s quite remarkable how the design goals set for TypeScript have stood the test of time." I am particularly intrigued by the goal of "Avoid adding expression-level syntax." One user even brought up thi ...

Tips for using Cookie Service in Angular 2

I am struggling to remove a specific cookie from my system and I don't have access to the necessary package that can help me resolve this issue. ...

Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads. The first input should have a value that is seven days prior to today's date, while the ...

The assigned type 'string' for Apache ECharts does not match the expected type 'pictorialBar'

This demonstration is functional. Nevertheless, the options utilize any and my goal is to convert them to the EChartOption type. This is my current progress and the demonstration compiles successfully with this setup (With type: 'bar' commented ...

Incorporating a filtering search bar in Ionic React to efficiently sort pre-existing lists based on their titles

Struggling to implement a search bar in my Ionic application has been quite challenging. I've searched for examples and tutorials, but most of them are based on Angular with Ionic. The React example in the Ionic docs didn't provide much help eith ...

Deducing the TypeScript function's return type based on the value it returns

Take a look at this scenario: type State = { sth: Something }; type Selector = <T>(state: State) => T; const selector: Selector = state => state.sth; I am hoping for the selector function to automatically determine its return type based on th ...

Unlocking the potential of Bootstrap 4 pop ups and modals within an Angular 6 project

Angular.json "styles": [ "./node_modules/bootstrap/dist/css/bootstrap.min.css", "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css", "src/styles.css" ], ...