Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario:

createNewList(oldList: any[]) {
 const newList = [];
 oldList.forEach(element => {
   if (element.isAwesome) {
     this.RESTCall().subscribe(result => {
       element.property = result;
       newList.push(element);
     });
   } else {
    newList.push(element);
   }
 });

 // need to wait here for all RESTCall elements before proceeding:
 return newList;
}

Your input on this matter would be greatly appreciated. Currently, with the restcalls taking longer, the function is transferring the list too early.

One solution could involve adding higher-level observables to a list, merging them with mergeAll (https://www.learnrxjs.io/learn-rxjs/operators/combination/mergeall), and then executing the complete() function. However, this approach seems overly complicated.

Do you have any insights or suggestions on how to simplify this process?

Answer №1

Transforming your existing list into a list of observables can greatly enhance its readability and maintainability.

const items = originalList.map(item =>
  item.isAmazing ? executeHttpRequest(item) : of(item));

executeHttpRequest(item: any): Observable<any> {
  return this.sendHTTPRequest().pipe(
    map(response => {
      item.data = response;
      return item;
    })
  );
}

Utilize the forkJoin method to combine all the results:

forkJoin(items).subscribe(updatedList => {
  console.log(updatedList);
})

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

Vue and TypeScript: The elusive 'exports' remains unidentified

Since switching my App.vue to utilize typescript, I am facing a compiler error: [tsl] ERROR in \src\main.ts(2,23) TS2304: Unable to locate the name 'exports'. If I have vue-serve recompile after making changes, I encounter t ...

What is the best way to retrieve the values of a select element from LEVEL 4 within the form submission of LEVEL 3?

To enhance readability, the intricate code has been abstracted. Within our Angular 2 project, we are working with a component called <top-component> (LEVEL 1): <top-component> </top-component> This component includes a template known a ...

Creating dynamic charts using Angular 7 with Chartjs and mapping JSON data

Struggling to map JSON Data for a Bar-Chart display. The desired final Array should be: [883, 5925, 17119, 27114, 2758]. Seems like the Array I'm trying to use for barChartData (dringlichkeitenValues[]) is empty. Apologies for my coding skills. Can so ...

What is the best way to fake the retrieval of '$location' using mock for angular.element(document).injector() in jasmine 3.6?

Currently, I am encountering an issue. I am unsure of how to mock the following method: private angularLocation = angular.element(document).injector().get('$location'); In my hybrid angular application, this method is crucial for navigating betw ...

Send a Date Object through an Event Emitter to be used in a Date Picker

I created a personalized Date Picker Child Component, and when the onDateChange event occurs, I intend to send an event to the parent component. @Output() selectedDateChange = new EventEmitter<Date>(); onDateChange($event) { this.selectedDateCha ...

Expanding mat-sidenav by clicking a button located outside of mat-sidenav-container

I attempted to replicate the mobile-friendly design seen in the Angular Material teams' example found on this link. Here is how I structured my component: <app-component-0></app-component-0> <div class="d-lg-none"> <button ...

The program encountered an issue: it cannot access the property 'invalid' because it is undefined

I have a scenario where I am utilizing nested FormGroup in Angular, with the parent formGroup in the HTML and skills as the nested form. However, during validation, the controls are not being found. Can anyone provide assistance with thi ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

Pagination feature in MUI DataGrid table is malfunctioning

I'm struggling to get the pagination feature to work in my Material UI DataGrid component, but I'm hitting a roadblock: https://i.stack.imgur.com/eT7s7.gif The console is not showing any errors. Here is the code for my component: import { ...

I'm struggling to find the right Typescript syntax for defining a thunk function that returns a value while using React Redux Toolkit

Currently, I am utilizing TypeScript within a React Redux Toolkit project. While attempting to create an Async Thunk action function that is expected to return a boolean value, I found myself struggling with determining the correct TypeScript syntax: expor ...

Is there a way to verify if the database has been successfully saved and the API call has been

I am currently in the process of developing a function that calls two other functions. Function 1 is responsible for saving an object to a database, while function 2 performs an API call. async createMSCalendarEntry(start: Date, end: Date, name: string ...

The proper approach for managing downloaded d.ts files from DefinitelyTyped after installation through npm

Visual Studio 2017 Enterprise ASP.NET MVC Application TypeScript 2.5 SDK Source control is in TFS I have opted to use Microsoft's built-in property editor instead of creating a custom tsconfig.config file: https://i.sstatic.net/VgcQO.png To streaml ...

Enhance your PrimeNG p-calendar by customizing the background-color of the dates

Hello, I am currently attempting to customize the appearance of the p-calendar, but I am struggling with changing the color of the displayed dates. Can anyone provide assistance? Thank you in advance. Below is my template: <div class="p-field p-co ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Angular bootstrap search is encountering an issue with locating a supporting object. It seems to be struggling to find a differ for the object of type 'object'

I recently delved into learning autoComplete Search. While I successfully retrieved the object from the backend server, displaying them in HTML resulted in the following error. NgbTypeaheadWindow.html:5 ERROR Error: Cannot find a differ supporting object ...

Is there a way to remove a button when it's clicked in Angular?

I have created a button component that is styled to resemble a pill for tab-focusability purposes. This button will be used to display keywords that a user searches for. I want the ability to remove or delete the displayed keyword by clicking on an X icon. ...

Methods for closing a modal popup on button click

In my AppComponent, there is a login button that triggers a SigninComponent modal popup when clicked. I am trying to figure out how to close the opened modal popup when a button is clicked. Below is the code snippet: app.component.html <ng-template # ...

I am working on two Angular projects and I am looking to integrate one of them into the other project

In my development work, I am juggling two Angular projects on Github: AngularApp1 and AngularApp2. AngularApp1 is a robust project with many components, while AngularApp2 serves a more specific purpose. My goal is to have a button in AngularApp1 that open ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

What causes the "Method Not Allowed" error while trying to restore the package.json package in VS2015?

When trying to restore a package.json file in VS2015, I am encountering a "Method Not Allowed" error. https://i.stack.imgur.com/OgK5P.png https://i.stack.imgur.com/AAkoQ.png The error log displays the following: npm ERR! Error: Method Not Allowed npm ER ...