DEV Community

Alejandro
Alejandro

Posted on

JHipster: Create filters dynamically in Angular

Sometimes, there are cases in which you need to filter your entities according to some conditions. For instance:

if (!this.searchShowOverdue) {
  this.invoiceService
    .filterInvoices({
      page: pageToLoad - 1,
      size: this.itemsPerPage,
      sort: this.sort(),
      'type.equals': this.invoiceType,
    }).subscribe(
      (res: HttpResponse<IInvoice[]>) => this.onFilterSuccess(res.body, res.headers, this.page),
        () => this.onError()
  );
} else {
  this.invoiceService
  .filterInvoices({
    page: pageToLoad - 1,
    size: this.itemsPerPage,
    sort: this.sort(),
    'type.equals': this.invoiceType,
    'status.equals': Status.OVERDUE,
  }).subscribe(
    (res: HttpResponse<IInvoice[]>) => this.onFilterSuccess(res.body, res.headers, this.page),
    () => this.onError()
  );
}
Enter fullscreen mode Exit fullscreen mode

Repeat this for as many conditions you need. So I started thinking about how much code that was and decided to do something about it.

As we all know, the service receives req: any like size: this.itemsPerPage in the example above.

What if I could fill that object according to our own conditions? Well, I did just that 😉

const req: Record<string, any>[] = [];
req.push({'page': pageToLoad - 1});
req.push({'size': this.itemsPerPage});
req.push({'sort': this.sort()});
req.push({'type.equals': this.invoiceType});
req.push({'active.equals': true});

if (this.searchShowOverdue) {
  req.push({'status.equals': 'OVERDUE'});
}
if (this.toDate && this.fromDate) {
  req.push({'date.lessOrEqualThan': this.toDate.format(DATE_FORMAT)});
  req.push({'date.greaterOrEqualThan': this.fromDate.format(DATE_FORMAT)});
}

const request = {};
(Object.values(req) as Array<any>).forEach(value => {
  request[Object.keys(value)[0]] = Object.values(value)[0];
});
this.invoiceService
  .filterInvoices(request)
  .subscribe(
    (res: HttpResponse<IInvoice[]>) => this.onFilterSuccess(res.body, res.headers, this.page),
    () => this.onError()
);
Enter fullscreen mode Exit fullscreen mode

As you can see, the code is cleaner and easier to add more filters.

I know this might not be the best solution, but it did help me clean a lot of code in my project, so it will do for now. If you have a better solution, please let me know 😃

Top comments (0)