What is the best way to execute multiple functions simultaneously in Angular?

Within a form creation component, I have multiple functions that need to be executed simultaneously. Each function corresponds to a dropdown field option such as gender, countries, and interests which are all fetched from the server. Currently, I call these functions individually in the ngOnInit lifecycle hook and it works correctly. However, I am curious if there is a more efficient way to execute these functions concurrently?

  ngOnInit() { 
    this.gender();
    this.countries();
    this.interests();
  }

  gender() {
      this.apiService.gender().subscribe((res: any) => {
      this.gender = res;
     }, error => {
     console.log(error);
     });
    }
  

  countries() {
      this.apiService.countries().subscribe((res: any) => {
      this.countries = res;
    }, error => {
     console.log(error);
     });
  }

  

  interests() {
      this.apiService.interests().subscribe((res: any) => {
      this.countries = res;
      }, error => {
     console.log(error);
     });
  }

Answer №1

Using forkJoin method:

  ngOnInit() { 
    forkJoin([this.getGender(), this.getCountries(), this.getInterests()]).subscribe();
  }


  getGender() {
      return this.apiService.gender().pipe(tap(gender => (this.gender = gender)));
  }


  getCountries() {
      return this.apiService.countries().pipe(tap(countries => (this.countries = countries)));
  }



  getInterests() {
      return this.apiService.interests().pipe(tap(interests => (this.interests = interests)));
  }

Answer №2

Here is an example of how you could structure your code:

initialize() {
   Promise.all([
      this.fetchDataOne(),
      this.fetchDataTwo(),
      this.fetchDataThree(),
   ]).then(() => {
      // Add the code you want to run after all data is fetched
   });
}

fetchDataOne(): Promise<void> {
   return new Promise((resolve, reject) => {
      this.apiService.getDataOne().subscribe((res: any) => {
          this.dataOne = res;
          resolve();
      },
          error => { 
             // Handle errors here
          }
      );
   });
}

Continue adding functions for the other data fetches.

Answer №3

If you want to implement the code below within the ngOnInit method:

ngOnInit() { 
      forkjoin(this.fetchGenders(), this.fetchCountries(), this.fetchInterests()).subscribe(() => {
          //perform actions after all calls have completed
      },
       (err: any) => {
          //handle errors generically
           console.log("error", err);
           this.isLoading = false;
       });
    );
}

Ensure that each of your methods follows a similar structure (to prevent breaking the chain in case of errors):

public fetchGenders(): Observable<any> {
    this.isLoading = true; //show loading indicator for user experience - utilized in html
    const fetchcGendersCallResult = this.http
        .get(...) //your endpoint
        .pipe(
            map((response: any) => response),
            tap(() => this.isLoading = false),
            catchError(...) //implement error handling for fetching genders
        );
    return fetchcGendersCallResult;
}

For further details, refer to this resource:

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

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

Why is my terminal showing certain output when I execute the command npm start?

I have a burning question. Upon running npm start in angular2, what exactly am I witnessing on my terminal screen? Where is this information originating from? I'm referring to: [1] No detection of a `bs-config.json` or `bs-config.js` override file. D ...

Encountering errors during 'npm i' - issues arising from unresolved dependency tree

Recently, I have been facing issues with running npm i as it keeps failing and showing an error. The project is using Angular 15 without any previous errors, so it's puzzling why there is suddenly a complaint about Angular 16. npm ERR! code ERESOLVE n ...

Unraveling the art of utilizing the map operator in ES6 with condition

I need to implement a condition within the map function where I prepend zeros for single digit values (00.00 to 09.30), while leaving remaining values unchanged. Currently, it is prepending zeros for all values. Here is the code: export class SelectOver ...

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

The process of HTML compilation is halted due to the unexpected presence of the forbidden 'null' data type, despite the fact that null cannot actually be a valid value in

Encountering an issue with my HTML code, where the compiler stops at: Type 'CustomItem[] | null | undefined' is not compatible with type 'CustomItem[] | undefined'. Type 'null' cannot be assigned to type 'CustomItem[] ...

Navigating with Tabs in Ionic Angular is a Breeze

Here is the routing configuration found in app-routing.module: const routes: Routes = [ { path: 'displayfile/:navitemid', loadChildren: () => import('./pages/file-viewer/file-viewer.module').then( m => m.FileViewerPageMo ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

The NGXS state does not get updated when a lazy loaded component is used

Recently, I started experimenting with the new lazy loaded components in Angular 9. I have a stateful component using NGXS with its state being lazy loaded in a module close to the component. However, after the component renders, the store does not update ...

Troubles with Angular animations not functioning properly

I want to create an entering animation for elements that appear on my page and are looped through using *ngFor. Even though I used a callback function to check if these animations have been triggered, they were launched but nothing was visible on the scree ...

Angular14 offers a unique highcharts speedometer with multiple dials in the gauge chart for a visually stunning

Looking to create a unique speedometer design with an inner dial and an additional triangular indicator using Highcharts gauge within the Angular14 framework. Is it possible to include an extra indicator with Highcharts gauge in Angular14? Click on the l ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

Verify if the Observable (HTTP request) has provided a response, and if not, hold for it?

In my Angular app, I have a calendarComponent that fetches entries from a MongoDB through firebase cloud functions using the calendarService. When creating a new entry, I display an addEventComponent dialog which requires data from the database to function ...

An Angular application caught in an endless cycle of redirects

Currently, I am working on an Angular project that involves the following routing configuration: const routes: Routes = [ { path: '', component: LoginLayoutComponent, children: [ { path: '', redi ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

EventListener cannot be removed

My TypeScript class is structured like this: class MyClass { let canvas: any; constructor(canvas: any) { this.canvas = canvas; this.canvas.requestPointerLock = this.canvas.requestPointerLock; document.exitPointerLock = ...

Encountered an error while attempting to execute Angular application due to schema validation failure

Encountering errors in my Angular 7 Application on the development server. After running ng serve, below is the error that surfaced: D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your global Angular CLI ...