Added foundation of a simple mock-api
This commit is contained in:
committed by
Erik Tiekstra
parent
81ac40ef31
commit
e1b8979b99
45
apps/dafa-web/src/app/services/api/participants.service.ts
Normal file
45
apps/dafa-web/src/app/services/api/participants.service.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
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) {}
|
||||
}
|
||||
Reference in New Issue
Block a user