Angular 8 datatables search not working as expected

Viewed 1104

I'm trying to use angular datatables to filter through data received from the server and I've encountered a problem. Search doesn't work (no error messages) when iterating through objects in a subscribe, but works when simply assigning values to my array of objects.

I've tried several different implementations I found online but none have seemed to work or weren't specific enough.

So this is the working code (credit.component.ts):

        getCreditList() {
        this.creditService.getCreditList().subscribe(credits => {
            this.credits = credits;
            console.log(this.credits); //outputs all credits as array of objects
            this.dtTrigger.next();
        });
    }

But when trying to filter the data in the promise, even tho the data displayed is correct, the search functionality of angular datatables is broken:

        this.creditService.getCreditList().subscribe(credits => {
            credits.forEach((obj, index) => {
                if (obj.deleted_at == null) {
                    this.credits.push(credits[index]);
                }
            });
            console.log(this.credits); // outputs all credits as array of objects where objects deleted_at property equals null
            this.dtTrigger.next();
        });
    }

In case there's a need for additional code here's related credit.component.html:

<table datatable [dtOptions]="dtOptions" class="row-border hover">
    <thead>
        <tr>
            <th>ID</th>
            <th>credit</th>
        </tr>
     </thead>
     <tbody>
        <tr
            *ngFor="let credit of credits; let i = index"
            class="col-12 table-row_{{ i }}"
        >
        <td>
            {{ credit.userid }}
        </td>
        <td>
            {{ credit.credit }}
        </td>
        </tr>
      </tbody>
</table>

Related credit.service.ts:

getCreditList() {
    return this.http.get<Credit[]>(this.url + 'credit');
}

Credit class:

export class Credit {
    id: number;
    credit: number;

    deleted_at: Date;
}

I expect to be able to preform a search with pre filtered data like in the working example.

If anyone could shine some light on this mystery it would be greatly appreciated.

Thank you!

Edit:

Pagination doesn't seem to work either, regardless of the aforementioned codes. I'm beginning to wonder maybe the problem is with async call, as in the data gets rendered too late or something? How would I go about solving this? Any help would be appreciated.

1 Answers

I know its a bad practice but for me it works if I put the trigger in a timeout like this:

setTimeout(() => {
   this.dtTrigger.next()
}, 1);
Related