refactor search service

This commit is contained in:
Dan Percic 2021-08-21 00:42:43 +03:00
parent e6e9fcdc72
commit b051f65c18

View File

@ -1,31 +1,19 @@
import { Injectable } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { map, startWith } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';
import { KeysOf } from '../utils/types/utility-types';
const controlsConfig = {
query: ['']
} as const;
type FormControls = { [key in KeysOf<typeof controlsConfig>]: string };
@Injectable()
export class SearchService<T> {
readonly searchForm = this._formBuilder.group(controlsConfig);
readonly valueChanges$ = this.searchForm.valueChanges.pipe(
startWith(''),
map((values: FormControls) => values.query)
);
private readonly _query$ = new BehaviorSubject('');
readonly valueChanges$ = this._query$.asObservable();
private _searchKey!: KeysOf<T>;
constructor(private readonly _formBuilder: FormBuilder) {}
get searchValue(): string {
return this.searchForm.get('query')?.value as string;
return this._query$.getValue();
}
set searchValue(value: string) {
this.searchForm.patchValue({ query: value });
this._query$.next(value);
}
searchIn(entities: T[]): T[] {
@ -40,7 +28,7 @@ export class SearchService<T> {
}
reset(): void {
this.searchForm.reset({ query: '' }, { emitEvent: true });
this._query$.next('');
}
private _searchField(entity: T): string {