Angular 10 introduces a new approach to handling concurrency called "forkJoin"

Here is the code I have:

 async getBranchDetails()  ----component  method

  {
    let banks = this.bankDataService.getBanks();
    let branchTypes = this.branchDataService.getBranchTypes();

    forkJoin([banks,branchTypes]).subscribe(results => {
              this.setFormBankData(results[0]);
              this.setFormBranchTypeData(results[1]);
            });
  }

----service

 async getBanks(): Promise<IBankResponse[]> {
        return await  this.httpClient.get<Result<IBankResponse[]>>(baseUrl + '/Bank/GetBanks')
        .pipe(map( res => res.data)).toPromise();
    }

Fork join is showing deprecated. Is there any alternative use with async/await. Thanks.

EDIT: i dont no whether it isright or not but used asyn/await..My final code as below

  async getBranchDetails()

  {
    let banks =  await this.bankDataService.getBanks();
    let branchTypes= await this.branchDataService.getBranchTypes();
    this.setFormBankData(banks);
    this.setFormBranchTypeData(branchTypes);
   
  }

Answer №1

You seem to be mixing Observables and Promises. It's best to choose one approach and stick with it - either Observables and RxJS, or just use Promises.

For the Observables approach (recommended):

getBanks(): Observable<IBankResponse[]> {
   return this.httpClient.get(baseUrl + '/Bank/GetBanks')
     .pipe(map(res => res.data));
}
const banks$ = this.bankDataService.getBanks();
const branchTypes$ = this.branchDataService.getBranchTypes();

forkJoin([banks$, branchTypes$]).subscribe(results => {
  this.setFormBankData(results[0]);
  this.setFormBranchTypeData(results[1]);
});

If you prefer the Promises approach:

getBanks(): Promise<IBankResponse[]> {
  return this.httpClient.get<Result<IBankResponse[]>>(baseUrl + '/Bank/GetBanks')
    .pipe(map( res => res.data)).toPromise();
}

When using Promises, you can utilize Promise.all for handling multiple requests:

const banks = this.bankDataService.getBanks();
const branchTypes = this.branchDataService.getBranchTypes();

Promise.all([banks, branchTypes]).then(results => {
  this.setFormBankData(results[0]);
  this.setFormBranchTypeData(results[1]);
});

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

Why do callbacks in Typescript fail to compile when their arguments don't match?

In my current project, I encountered a scenario where a React callback led to a contrived example. interface A { a: string b: string } interface B { a: string b: string c: string } function foo(fn: (a: A) => void, a: A) { fn( ...

Having trouble sending a x-www-form-urlencoded POST request in Angular?

Despite having a functional POST and GET service with no CORS issues, I am struggling to replicate the call made in Postman (where it works). The only thing I can think of is that I may have incorrectly set the format as x-www-form-urlencoded. When searchi ...

What steps can I take to ensure that a function is only executed after at least two Observables have returned data?

I am currently working on an Angular Reactive form that incorporates custom components. The form includes basic Form Fields and a Froala editor, customized with dropdowns that fetch values from the backend using observables. This is where I encounter some ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

The design of Next.js takes the spotlight away from the actual content on the

Recently, I've been working on implementing the Bottom Navigation feature from material-ui into my Next.js application. Unfortunately, I encountered an issue where the navigation bar was overshadowing the content at the bottom of the page. Despite my ...

I am experiencing slow load times for my Angular 2 app when first-time users access it, and I am seeking assistance in optimizing its speed

Below, you'll find a snippet from my app.ts file. I'm currently working with angular2, firebase, and typescript. I'm curious if the sluggish performance is due to the abundance of routes and injected files? The application functions smoot ...

The method for retrieving the value of a FormControlName in an array format for multiple select fields

Within this loop, I am iterating through the div multiple times and collecting all the select element values into a single array while replacing certain indexes. For instance, if I have four select elements in my HTML, there will be four select fields on ...

Tips for preserving @typedef during the TypeScript to JavaScript transpilation process

I have a block of TypeScript code as shown below: /** * @typedef Foo * @type {Object} * @property {string} id */ type Foo = { id: string } /** * bar * @returns {Foo} */ function bar(): Foo { const foo:Foo = {id: 'foo'} return f ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

Custom styles for PrimeNG data tables

Struggling to style the header of a datatable in my Angular project using PrimeNG components. Despite trying various solutions, I am unable to override the existing styles. Even attempting to implement the solution from this PrimeNG CSS styling question o ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

Using Pydantic to define models with both fixed and additional fields based on a Dict[str, OtherModel], mirroring the TypeScript [key: string] approach

Referencing a similar question, the objective is to construct a TypeScript interface that resembles the following: interface ExpandedModel { fixed: number; [key: string]: OtherModel; } However, it is necessary to validate the OtherModel, so using the ...

Exploring the world of Angular CLI testing and the versatility of

Struggling with integrating Angular CLI's test framework and enum types? When creating an enum like the following (found in someenum.ts): const enum SomeEnum { Val0, Val1 } Utilizing it in this way (in app.component.ts): private someEnum = Some ...

I am verifying the user's login status and directing them to the login page if they are not already logged in

My goal is to utilize ionViewWillEnter in order to verify if the user is logged in. If the check returns false, I want to direct them to the login page and then proceed with the initializeapp function. My experience with Angular and Ionic is still limite ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Creating a custom design for ng-bootstrap accordion using CSS styling

I've encountered an issue with my Angular 2 component that utilizes an accordion from ng-bootstrap. While the functionality works perfectly, I'm facing a problem with applying custom styles using the .card, .card-header, and .card-block classes o ...

Item removed from the cache despite deletion error

Currently, I am utilizing Angular 8 along with @ngrx/data for handling my entities. An issue arises when a delete operation fails (resulting in a server response of 500), as the entity is being removed from the ngrx client-side cache even though it was not ...

What is the best way to send serverside parameters from ASP.Core to React?

After setting up a React/Typescript project using dotnet new "ASP.NET Core with React.js", I encountered the following setup in my index.cshtml: <div id="react-app"></div> @section scripts { <script src="~/dist/main.js" asp-append-versi ...

Can the Angular Material Mat Stepper display multiple active/in-progress steps simultaneously?

Has anyone figured out how to display multiple steps simultaneously on Angular Mat Stepper? I've only been able to show one step at a time and haven't found a solution yet. Any insights would be greatly appreciated. https://i.stack.imgur.com/VK ...