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

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Changing the name of a tab within a p-tabview

Setting up a p-tabview with tabs containing specific content involves the following code: <p-tabView class="tabmain" > <ng-container *ngFor="let tab of tabs"> <p-tabPanel [header]="tab.header" > ...

Creating a constant.ts file to define universal constantsWould you like assistance with anything else

Is there a way to create a constant.ts file or use a command to declare all global constants and export them for easy access? ...

What causes TypeScript to struggle with inferring types in recursive functions?

Here is a code snippet for calculating the sum: //Function to calculate the sum of an array of numbers let sum = ([head, ...tail]: number[]) => head ? head + sum(tail) : 0 let result: string = sum([1, 2, 3]); alert(result); Can anyone explain why ...

No routes found to match. URL Segment: ''. This issue occurs when attempting to utilize child routes with Angular 2

I am having issues with this specific plunker that seems to not be working correctly. To try and fix the problem, I attempted to comment out a section of code... RouterModule.forRoot([ { path: "", component: TestComponent, ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Is there a similar feature to RxJs version 4's ofArrayChanges in RxJs version 5?

Currently utilizing Angular2 and attempting to monitor changes in an array. The issue lies with only having RxJs5 available, which appears to lack this specific functionality. ...

When using Angular, it is important to remember that calling `this.useraccount.next(user)` may result in an error stating that an argument of type 'HttpResponse<any>' cannot be used with a 'Useraccount' balance

When attempting to use this.useraccountsubject(user) to insert information upon login, I encountered an error: ErrorType: this.useraccount.next(user) then Error An argument of type 'HttpResponse' is not allowed against a balance of 'Userac ...

Employing the reactive forms approach for validation instead of ngModel logic

Exploring the realm of Angular's form validation, I find myself torn between two routes. However, I am on a quest to merge the strengths of each and reach a solution that resonates with me. Delving into the technicalities, I come across the FormBuild ...

Use the res.json method in express.js to automatically generate a predefined response structure

I'm looking for guidance on how to properly use res.json in my code. I want to establish a default response structure that includes a message and error, while also being able to include additional data when necessary. For example, when I use res.statu ...

Subclass method overloading in Typescript

Take a look at this example: class A { method(): void {} } class B extends A { method(a: number, b: string): void {} } An error occurs when trying to implement method() in class B. My goal is to achieve the following functionality: var b: B; b.met ...

Tips for resolving: Dilemma - Angular configuration loaded in both synchronous and asynchronous manner

I recently updated my Angular 6 project to Angular 11. The project includes server-side rendering (SSR), and I am encountering an issue. After running ng run myapp:server, I am getting the following error: ✔ Server application bundle generation complete ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

Logging out of an application that utilizes IdentityServer4 with ASP.NET Core MVC and Angular integration

I am encountering an issue related to the proper return to the client application after a successful logout. Before delving into the problem, let me provide some background information about my current setup: IdentityServer4 serves as the Identity Provid ...

TypeScript is failing to identify a correctly typed property

Currently, I am facing issues while converting a Material UI Dashboard from React to Typescript. The problem arises during TypeScript compilation where the property in question meets the criteria mentioned in the error message. To put it briefly, the compi ...

Utilizing Ngrx store for Reacting form validation with the integration of asynchronous validation

I'm currently working on an Angular 8 project where I aim to showcase form errors through NgRx store while utilizing reactive forms with a custom asynchronous validator. login.component.ts @Component({ selector: 'auth-login', templateU ...

Unable to link with 'NgModel' as it is not recognized as a valid property of 'ion-input'

I'm experiencing some difficulty with the following error message: Error: Uncaught (in promise): Error: Template parse errors: Can't bind to 'NgModel' since it isn't a known property of 'ion-input'. 1. If 'ion-input ...

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

What is the reasoning behind exporting it in this manner in the index file?

As I was going through a tutorial about nests, there was this step where the instructor made a folder named "dtos" and inside it, they created two dto files (create-user.dto and edit-user.dto). Following that, they also added an index file in the same fold ...