Files
mina-sidor-fa-web/apps/dafa-web/src/app/services/api/participants.service.ts
2021-03-24 15:27:02 +01:00

46 lines
1.5 KiB
TypeScript

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<Participant[]> = this.httpClient.get<Participant[]>(
`${environment.apiBase}/participants`
);
private _sortBy$ = new BehaviorSubject<SortBy | null>({ key: 'service', reverse: false });
public sortBy$: Observable<SortBy> = this._sortBy$.asObservable();
public participants$: Observable<Participant[]> = 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) {}
}