Leveraging Angular 2 to send multiple requests with the help of rxjs

My angular2 app has a feature where it adds or removes items from a multiple select box and sends each item to a remote api individually for processing in the database. The method below is used to send the request to the server and receive a response as an observable:

removeFromClientLibrary(username: string, roleID: string): Observable<any> {
        let body = JSON.stringify({Key: username, Value: roleID});

        return this._http.post(this._removeFromLibraryURL, body, this.emsConfig.getStandardHttpHeaders())
            .map((res:Response) => <any>res.json());
    }

I have set up a client to consume this by using the subscribe method. I initially thought that calling subscribe once should suffice, but for some reason it doesn't work that way. The only way I could get the desired result was to loop through each item and subscribe multiple times like so:

for (let i = 0; i < selected.length; i++) {
  this._accountsService.removeFromClientLibrary(this.username, selected[i].RoleID)
    .subscribe(status => {          
      console.log(status);
    });
}

I'm wondering if there's a more efficient way to handle the API results using rxjs without having to subscribe multiple times as shown above. Is there another approach to fetching the data?

Answer №1

To achieve this, you can utilize the combineLatest operator.

Observable.combineLatest(
  selected.map(selectedId =>
    this._accountsService.removeFromClientLibrary(this.username, selected[i].RoleID)))
)
  .subscribe((statusArray) => console.log('all tasks complete: ', statusArray));

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

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Form remains unchanged after manipulation in callback

Currently, I have a form with a list of editable objects (constants). Previously, it was possible to delete any object without confirmation. Now, I want to add a ngBootbox confirm step before the deletion process. In my .ts file, the code for deleting an ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...

Discover the method for extracting a value from an interface and incorporating it into a separate function

I need help accessing the value of userType for a conditional statement. UserType: const RadioForm = (props) => { return ( <div> <label>Customer</label> <input type="radio&qu ...

How to import a page from a different component in the Next.js application router

I am currently utilizing the Next.js app router and have organized my folders as follows: app/ ├─ /companies/ │ ├─ page.tsx ├─ /administrators/ │ ├─ page.tsx My objective is to import the companies/page.tsx component into the admini ...

Promise of a repeating sequence of serial calls

I am looking to create a recursive serial call to the promise method times, which will return the result of calling the fn function N times and storing the results in an array. To achieve this, I have added a new attribute called results to the times func ...

I'm having trouble displaying my Angular project on Localhost:4200

I am facing an issue with my localhost:4200 where it is not displaying anything from my project. It was working fine before but after making some changes like generating a new component and modifying it, the page appears blank now.see image here see image ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Encountering an error in Angular when trying to add a dynamic component

I have a straightforward test code for implementing dynamic components in Angular 4. @Component({ selector: 'component', template: ` <ul><li #item *ngFor="let number of list">{{number}}</li></ul> <ng-temp ...

Angular not sending Http Post requests

I've been attempting to grasp the concept of sending an HTTP POST request to my API service using Http (not Http Client), but the request doesn't seem to be received. The URL is correct, and the API name matches properly... After some initial a ...

Tips for successfully transferring a JsonifyObject<T> from Remix's useLoaderData<typeof loader> to a function

Encountering a TypeScript error while trying to import JsonifyObject in the Remix 2.9.2 route code below... Argument of type 'JsonifyObject<IdAndDate>' is not assignable to parameter of type 'IdAndDate'. Struggling to figure ou ...

Troubleshooting the 'Buffer' name not found error occurring in an Angular application

While working on my application, I started encountering this error message out of nowhere. Everything was functioning correctly before, and I'm clueless as to what could have caused these errors to pop up. I attempted to address the issue by installin ...

Implementing centralized authentication through an IdentityServer application with the utilization of the resource owner password flow

I am currently developing two Angular 2 applications that will have a .NET Core 1.1 REST backend and be hosted on Azure App Service. My goal is to enable them to share authentication information in order to provide a seamless Single Sign-On experience. Add ...

Creating separate components for mobile and desktop views in Angular, while also incorporating server-side rendering (SSR)

I'm in the process of creating a website that will have different layouts for Desktop and Mobile screens. To accomplish this, I've utilized separate routing mechanisms based on the device's width. Here is an example. import { NgModule } fro ...

The compiler is showing an error with code TS5023, indicating that the option 'strictTemplates' is not recognized

When trying to compile my Angular application (v10), I encountered the following error message. An unexpected issue has occurred: tsconfig.json:14:5 - error TS5023: Unknown compiler option 'strictTemplates'. 14 "strictTemplates": t ...

Encountering an Error While Trying to Add Typescript Support to Create React App Using Yarn

Encountering an issue while setting up a new Typescript/React project. Here's the error message: Installing template dependencies using yarnpkg... yarn add v1.22.19 [1/4] Resolving packages... [2/4] Fetching packages... error <a href="/cdn-cgi/l/em ...

Step-by-step guide to appending a log at the beginning and conclusion of the Observable

My task requires executing specific actions both at the start and the end. Desired Outcome: Begin by printing a starting log, then wait for 3000ms before displaying 'hello world!' followed by 'end'. import { Observable, finalize, timer ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

What steps can I take to avoid an invalid operation on a potentially null reference in typescript?

Take a look at this scenario where the variable a can potentially be null, and is explicitly defined as such. Even when strict null checks are enabled, TypeScript does not flag a possible issue in this situation - let a: string | null = "hello" function ...