Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call.

The first API call fetches something like this:

[0001,0002,0003,0004,0005]

I then iterate over these story IDs and pass them into the card component:

<div *ngFor="let id of storyIds | slice: start:end">
    <app-cards [id]="id"></app-cards> 
</div>

Once the second API is called based on the IDs from the card component, it returns responses for each ID:

{name: 'John', score: 1}
 {name: 'Jane', score: 99}
 {name: 'Joe', score: 53}

At this point, I am trying to figure out how to sort these items based on the scores provided by the second API call. One approach could involve pushing each object into an array and sorting this new array of objects.

Answer №1

To optimize performance, it is recommended to simplify app-cards and pass the fetched story data directly to them.

Component

this.service.fetchStories().pipe(
  switchMap(idArray => forkJoin(idArray.map(id => this.service.fetchStoryItems(this.id)))),
  map(storyArray => storyArray.sort((a,b) => a.score - b.score)),
  take(1),
).subscribe(res => {
  this.stories = res;
});

HTML

<div *ngFor="let story of stories | slice: start:end">
    <app-cards [story]="story"></app-cards> 
</div>

Avoid making HTTP calls within the app-cards component for better efficiency.

Answer №2

What do you think of

this.data = res.sort( (x,y) => x.grade - y.grade);

Answer №3

You have the ability to customize the output data from your subsequent API call

this.service.fetchStoryItems(this.id)
.pipe(
  take(1),
 map(response => {
    return {...response, id: this.id
  })
)
.subscribe((res: StoryItem) => {
  if (res !== undefined) {
    this.data = res;
    console.log(this.data) // should contain the id and be sortable using a comparison function
  }
})

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

The update feature seems to be malfunctioning within the MEAN Stack environment, specifically with node.js and angular js

Looking for some assistance as a beginner in the mean stack. I'm trying to update a record using the update function, but it's not working as expected. I need to update a specific object based on its ID, however, I'm encountering issues wit ...

Could it be possible for TypeScript inference to directly infer the value and omit the key in the process?

class A { state: B } class B { something: C } class C { a: string; b: boolean; } type MagicType = ... const c: MagicType<A> c.state.a = "123" c.state.b = true; Is it possible to achieve the mentioned functionality without altering the exi ...

Different Zoom feature for JIT Graph

I'm currently working with the Java Infovis Toolkit and I'd like to use buttons for zooming in and out instead of using the mouse wheel. Can someone guide me on how I can implement two separate buttons for Zoom In and Zoom Out functions? ...

Error: Attempting to access a property called 'sign' on an undefined value

I encountered an issue while signing my transaction where I received an error message stating sendTransaction needs signer. Even though both message (encrypted using keccak256) and signer have values, I am unsure why there is a problem when executing the w ...

JavaScript Grouping Arrays

I am working with an array and need to filter it by both Country and Service. So far, I have successfully filtered the array by Country. Now, I want to achieve the same filtering process based on the Service as well. Here is a snippet of the array: [ ...

Shopping Dialog with Bootstrap (nakupanda) captures form input [JSFiddle]

Having difficulty extracting data from my form. Currently utilizing the bootstrap dialog from nakupanda () The dialog (located within a fullcalendar select function) var form = $('#createEventForm').html(); BootstrapDialog.show({ mes ...

Fixing Half Screen Sidebars

I have a query regarding my coding problem. I am trying to create two pop-ups that occupy half of each screen. As I am new to JavaScript and jQuery, I want to ensure that I am doing it correctly. Is there a way for the left side to slide out from the left ...

Storing data in Angular 2's ngFor loop for later usage

I have a list of different types created by a for loop. Each type in the list has a delete button next to it, allowing users to remove that specific item. Clicking on the delete button opens a modal where the user can confirm the deletion. To avoid having ...

Elevate your software from Angular 13 to 14 for Improved Routing Performance

Since updating to version 14, I've encountered the following error: An error occurred due to an invalid configuration of route 'map/operator/': a componentless route without children or loadChildren cannot have a named outlet set Below is ...

What is the most creative way you can think of to create a CSS/JS animated

Is using an animated SVG the best way to create these wavy blobs for mobile compatibility? What approach would you take? Here is a similar example I found var wave = document.createElement("div"); wave.className += " wave"; docFrag.appendChil ...

exploring the depths of nested objects and utilizing the 'for in

My issue involves receiving a json response from an API that includes objects within objects. It looks something like this: {Object}->{results}->{manyObjects} When I execute the following code: var list = data.results.list; for(val in list){ ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

How to easily toggle icons on a primeNg tree when there are no children using Angular 8

The toggle icon in the p-tree is only visible if the tree has children. I want to display it using my own property in data: haschildre. Here is the json Components structure of my tree: { label: 'Documents', data: [{ id: 1, name: 'M ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...

Why is React JS unable to discover my exported modules?

Upon running my React app, the console displayed the following error message: Failed to compile. ./src/components/login/index.js Attempted import error: 'Login' is not exported from './login'. Here is an overview of the folder struct ...

Looking for a method to efficiently populate an array with values in Typescript

Here is an example of how I work with arrays in my code: var alphas: string[]; alphas = ['abc1', 'abc2', 'abc3']; // (this array can be changed) My modal class looks like this: export class Team { TeamName: string; } To ...

Insert a variable into the URL path of a JavaScript file

Struggling to insert a variable in the code snippet below: eleventyConfig.addPassthroughCopy({ "random-folder/img": "subfolder/img" }); This is what I've attempted: var directory = "random-folder"; eleventyConfig.addPassthroughCopy({ directory + "/ ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...

Utilizing Angular 4's piping feature to manipulate data sourced from an API observable within

I am currently working on setting up a filter for my stories. After subscribing to the API call, I receive the data in the form of an array of objects. However, I am encountering an error while trying to apply filters. Here is a snippet of relevant inform ...