0

i have this code that calls an api for every object of a list "titles" and add the object to another list "groupDocs". but since the response of the api is not immediate the order of objects changs in the list "groupDocs". what should i do to keep the same order?

i can't find a solution to this problem and i am new to 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,
                    'Une erreur est survenue lors du chargement de la liste des contrôle d\'erreurs');
            }
        );
    }
}
alma elghoul
  • 183
  • 1
  • 2
  • 12
  • What do you mean 'order changes'? New items appear in random positions? What is the desired behavior? – Anton Rusak Oct 25 '19 at 12:07
  • 1
    You should sort your list based on your specific sort rule. – Florian Oct 25 '19 at 12:12
  • when i debug loop starts item by item it calls "this.controlErrorService.getErrorControl(criteria)", at the fifth item i start getting response the fifth element is added to the groupdocs list what i want is to keep the order this behavior changes the order of my objects – alma elghoul Oct 25 '19 at 12:27

1 Answers1

1

As Florian said, you should sort the list by titles. This can be done 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()));

Or, much better, with a custom pipe in the template:

ngFor*="let doc of groupDocs | sortByTitle"

You can get the idea about how to create such pipe in this SO answer. And do not forget to add the pipe into angular declarations array.

Anton Rusak
  • 882
  • 4
  • 18