What is the best way to invoke a service within a for loop?

private Payload(): asset { 
    const payload = { //pay load }
    return payload; 
}
  
public listofnumbers() { 
    number = [1,2,3]; 
    number.forEach(element => { 
        this.service(element); 
    }); 
}
 
private service(number) {
    this.service.getNumbers(this.Payload())
        .subscribe((res) => { 
            if (res.isSuccess && res.data) { 
                this.function(); 
            } 
        }) 
} 

function () { alert("fghj"); }

When the service is called, instead of executing the HTTP call first, it calls a method inside the service. Feeling confused about what to do next?

Consider using forkjoin

 public sendSelectedToD365() {
    let assetDetails1 = [];
      let assetSearchValue =(this.searchAssetForm.controls['assetSearch'].value).split(',');
      let mycalls = assetSearchValue.map(x => this.trying(x))
      forkJoin(mycalls).subscribe(res => {
        console.log(res)

      })
    }

  private trying(x)
      {     this.assetService.getAssetDetails(this.AssetDetailsPayload(x)).subscribe((res) => {
            if (res.isSuccess && res.data) {
              return res.data;
            }
        })
    }

Not happy with the current implementation? Try using forkjoin, but it's not working as expected.

Answer №1

Hello @Sanjana, remember that the "key" to forkJoin is to "join" observables together, so when "trying" you should expect an observable to be returned

  public sendSelectedToD365() {
      let assetDetails1 = [];
      let assetSearchValue =(this.searchAssetForm.controls['assetSearch'].value).split(',');
      let mycalls = assetSearchValue.map(x => this.attempting(x))
      forkJoin(mycalls).subscribe(res:any[] => {
        console.log(res)
        // in res[0] you will find the response to the first call
        // in res[1] you will find the response to the second call
        // ...
        res.forEach((x,index)=>{
          console.log("The response to",assetSearchValue[index],"is",res[index])
        })

      })
    }

  private attempting(x):Observable<any>
  {         
       // note that the return type is an Observable
         return this.assetService.getAssetDetails(this.AssetDetailsPayload(x))
  }

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

Challenges encountered while implementing Cognito API with Angular's HttpClient and HttpHeaders

Recently, I've been facing a dilemma between HttpClient and Axios. When I implement the following code: const requestBody = { grant_type: 'refresh_token', client_id: environment.APP_COGNITO_CLIENT_ID, refresh_token: thi ...

Unlock the key to connecting the output of one observable to another in rxjs

I have a procedure for saving users in the database. These are the steps I take: 1) First, I validate the request. 2) Next, I hash the password. 3) Finally, I store the user details in the users collection along with the hashed password. Below is the ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Setting up validators for an entire FormGroup in Angular ReactiveForms can be achieved by iterating through the

In my current project, I am dealing with a complex form that includes multiple fields. For each field, I have implemented various validators to ensure data integrity. For example, for the 'surname' field, I have the following validators: this.s ...

New data field is created with AngularFire2 update instead of updating existing field

I am facing an issue with updating a Firestore model in Angular 6. The model consists of a profile name and a list of hashtags. The "name" is stored as the value of a document field, while the "hashtags" are stored as keys in an object. However, every time ...

Make sure to refresh the state of the store whenever there is a change detected in the input

I am experiencing an input delay problem when trying to update the state of a zustand variable in the onChange event. const BuildOrder = (props: { setOpen: Function }) => { const { almacenes, isLoadingAlmacenes } = useGetAlmacenes(); const { article ...

A notification pop-up will only appear the first time after sending a repeated action

When testing my snackBar functionality by inputting incorrect user credentials multiple times and submitting the form, I encountered an issue. The snackBar only appears the first time, not every time an error or success message is dispatched. Below is the ...

The installation of Angular CLI through npm has unfortunately encountered an error

After following the steps from this post to remove the old installation, I encountered an issue during the last step: [sudo] npm uninstall -g @angular/cli [sudo] npm cache verify [sudo] npm install -g @angular/cli During the final step, I faced difficult ...

Top choice for React with TypeScript CodeMirror integration

Seeking recommendations for a package that seamlessly integrates with typescript in an existing react application. Specifically, looking to implement codeMirror functionality. Any suggestions? ...

Determine the return type based on the input parameter and a mapping strategy

I am encountering an issue with the inferred returnType of the following types. The problem lies in the cityAttractions type, where it should ideally have a type error in its return statement for returning a string instead of an array of strings. Playgrou ...

Fetching data from one component to load an Angular component

Essentially, I have a grid within Ionic that dynamically populates its rows using ngFor. Each row contains an ionic button labeled "View details" which, when clicked, should display all the data associated with that specific object. Imagine it as a preview ...

TypeScript and Node.js: The type of 'this' is implicitly set to 'any'

Help Needed with TypeScript issue: An issue is arising in my TypeScript code related to a mongoose schema's post function. It is used to generate a profile for a user upon signing up, using the User model. Even though the code functions properly, th ...

Determining in Angular 8 whether a value has been altered by a user or by a method call

Within my select element, the value is currently being assigned through an ngOnInit call. Here is an example of the HTML code: <select name="duration" [(ngModel)]="exercisePlan.duration" (ngModelChange)="onChange($event)"> <option *ngFor="l ...

Angular has the feature of a right float button with *ngfor

I've successfully implemented a form using Reactive Forms in Angular. Currently, my form is displayed as follows: <div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let ...

Tips for deploying an Angular Universal 9 application on a live server

Our Angular 9 app functions perfectly when deployed on an IIS server. We also have a version of the app that has been integrated with Universal by another company. Now, we need to figure out how to deploy our app with server-side rendering into productio ...

Utilizing TypeScript interfaces with additional parameter object members does not result in the anticipated compilation error

Consider the different types listed below: type Person = { id: string; name: string; }; interface PeopleRepository { getPerson(query: { id: string }): Person; } class Repository implements PeopleRepository { getPerson({ id, age }: { id: string; ...

Access the Angular application directly from the email

Our infrastructure consists of a .NET back-end, an Angular 5 application, and a nginx server. Upon registering your account in the application, you will receive an email with a verification link structured as follows: [root]/register/verify?userId=blabla& ...

Struggling to understand the usage of FromBody in ASP.NET Core

In my current project, I have a WEB API method that interacts with a SPA template built using Angular: [HttpPost] public IActionResult Post([FromBody]MyViewModel model) After reading a discussion on this topic, I was under the impression that including [ ...

Guidelines for creating a masterpage and details page layout in Angular 6

In my app.component.html file, I have the following code: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> </div> <div> <p-menu [model]="items"></p-menu> </div> Below is the code ...

Retrieve the accurate file name and line number from the stack: Error object in a JavaScript React Typescript application

My React application with TypeScript is currently running on localhost. I have implemented a try...catch block in my code to handle errors thrown by child components. I am trying to display the source of the error (such as file name, method, line number, ...