import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from '@dafa-environment'; import { Participant } from '@dafa-models/participant.model'; import { SortBy } from '@dafa-models/sort-by.model'; import { BehaviorSubject, combineLatest, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class ParticipantsService { private _participants$: Observable = this.httpClient.get( `${environment.apiBase}/participants` ); private _sortBy$ = new BehaviorSubject({ key: 'service', reverse: false }); public sortBy$: Observable = this._sortBy$.asObservable(); public participants$: Observable = combineLatest([this._sortBy$, this._participants$]).pipe( map(([sortBy, participants]) => { if (sortBy) { const reverse = sortBy.reverse ? -1 : 1; return [...participants].sort((a, b) => { const first = a[sortBy.key]; const second = b[sortBy.key]; return reverse * +(first > second) - +(second > first); }); } return participants; }) ); public setSortKey(key: keyof Participant) { const currentSortBy = this._sortBy$.getValue(); let reverse = false; if (currentSortBy?.key === key) { reverse = !currentSortBy.reverse; } this._sortBy$.next({ key, reverse }); } constructor(private httpClient: HttpClient) {} }