Angular 7 introduces updates to the way lists are ordered

I am facing an issue with my code that calls an API for each object in a list called "titles" and then adds the object to another list named "groupDocs". However, due to the asynchronous nature of the API response, the order of objects in the "groupDocs" list gets jumbled. What can I do to ensure that the order stays consistent?

I have been unable to find a solution to this problem as I am still new to working with Angular.

public getDetails(titles: ErrorTitleData[]): void {
    for (const title of titles) {
        const showButtons: boolean = false;
        const details: controlErrordetailsData[] = [];
        const criteria: SearchCriteriaControlData = {
            aggFields: ['Famille', 'Sous-Famille', 'Date', 'Controle', 'erreur'],
            page: 0,
            step: 20,
            selectedValues: {},
            queryString: ''
        };

        criteria.selectedValues['Sous-Famille'] = [title.sf ? title.sf : ''];
        criteria.selectedValues['Date'] = [title.dateVerif ? title.dateVerif : ''];
        criteria.selectedValues['Controle'] = [title.typeVerif ? title.typeVerif : ''];

        this.controlErrorService.getErrorControl(criteria).subscribe(
            (data) => {
                data.hits.forEach(element => {
                    const detail: controlErrordetailsData = new controlErrordetailsData(element);
                    details.push(detail);
                });

                this.groupDocs.push(new GroupDoc(title, details, criteria, data.total));

            },
            (error) => {
                this.toastService.update(ToastService.TYPE_ERROR,
                    'An error occurred while loading the list of control errors');
            }
        );
    }
}

Answer №1

In the words of Florian, it is recommended to arrange the list by titles. This task can be achieved in TS code:

this.groupDocs.push(new GroupDoc(title, details, criteria, data.total));
this.groupDocs = this.groupDocs.sort((doc1, doc2) => doc1.getTitle().localeCompare(doc2.getTitle()));

Alternatively, a more efficient approach would involve using a custom pipe within the template:

ngFor*="let doc of groupDocs | sortByTitle"

To understand how to develop such a pipe, refer to this answer on SO. Do not overlook adding the pipe into the angular declarations array.

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

Encountering Error 404 while submitting a form on Prisma, Axios, and NestJS

Currently, I am working on a Sign Up page using SolidJs and NestJS with Prisma. However, when I try to submit the form, I encounter an error that says POST 404 (Not Found) and this error is also returned by axios. Additionally, my setup includes postgres ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

What is the best way to bring in a SCSS file within another SCSS file?

When working with SCSS, I find myself using a lot of variables. To keep things organized, I create a separate file that contains all of my SCSS variables. The next step is to import this file into other SCSS files. Here's what I tried: Create a fil ...

Issue with host-context scss rules not appearing in final production version

I am facing an issue in my Angular project where the scss rules that define how components should look when within the context of another component are not being applied when I build for production and put it live. Here is an example: :host-context(my-tabl ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

The HighCharts is displaying an error message stating "Unable to detect the property 'series' as it is

Is there a way to retrieve all data along with the chart type and other details, but I keep encountering this error: Cannot read property 'series' of undefined. Below are the component.ts and service file: const sampleData: Overview[] = [ ...

What is the best way to accept user input in typescript?

Currently, I am working on a TypeScript project that involves taking user input for the addition of two numbers. Below is the code snippet I am using: function rotatedString(S1,S2){ return S1+S2; } function processData() { //INPUT[uncomment & m ...

What are the steps to enable full functionality of the strict option in TypeScript?

Despite enforcing strict options, TypeScript is not flagging the absence of defined types for port, req, and res in this code snippet. I am using Vscode and wondering how to fully enforce type checking. import express from 'express'; const app ...

In the case of an Angular application, what is the reason behind hotkeys not functioning in Chrome until the user actively engages with the webpage

When using Angular, I have set up various HostListeners to listen for keydown events: @HostListener('window:keydown', ['$event']) keyEvent(evt: KeyboardEvent) { console.log(evt) } I observed in the console logs that these listeners a ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

Matching list symbols in regular expressions (Angular 2)

I have been attempting to find a solution for matching a list of symbols using regex, but I keep encountering errors in the result. The symbol list includes: !@#$+*{}?<>&’”[]=%^ if (text.match('^[\[\]\!\"\#&bs ...

Can the contents of a JSON file be uploaded using a file upload feature in Angular 6 and read without the need to communicate with an API?

Looking to upload a JSON file via file upload in Angular (using version 6) and read its contents directly within the app, without sending it to an API first. Have been searching for ways to achieve this without success, as most results are geared towards ...

Tips for updating static array data with API requests in Angular

How can I replace the existing static array data with the response data from an API request? Below is a sample array of data that I would like to replace with the data obtained from the API response. How should I go about accomplishing this task? I am cu ...

Angular 2: Testing Firebase Add Functionality with Unit Tests

Is there a way to perform a basic unit test in Angular 2 for testing a simple firebase adding item feature? I've opted for typescript over standard JavaScript in my code. This is the piece of code I want to test: export class AppComponent { r ...

Why does the data appear differently in Angular 9 compared to before?

In this particular scenario, the initial expression {{ bar }} remains static, whereas the subsequent expression {{ "" + bar }} undergoes updates: For example: two 1588950994873 The question arises: why does this differentiation exist? import { Com ...

The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3: When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating The AWS Access Key Id you provided does not exist ...

JSON Object Key passed as a parameter in a function

While I have seen a similar question before, I am still unsure how to apply the solution in my specific case. I am working with a function that returns a stringified JSON object, but I need to modify one of the keys using a parameter within the function. ...

Tips for toggling visibility in Angular 2

I utilized [hidden] in the following way where the value of "secondTab" is set to true. <form #siteForm="ngForm" novalidate (ngSubmit)="saveSite(siteForm.value,siteForm.valid)" class="admin-modal"> <div class="txt-danger">{{errorMessage}}&l ...

Using React.Fragment in VS Code with TypeScript error 2605 while having checkJs enabled

While utilizing the JS type checking feature in VScode, I encountered an issue with React.Fragment that is being linted with an error: JSX element type 'ReactElement<any>' is not a constructor function for JSX elements. Type 'ReactEle ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...