Skip to content

Instantly share code, notes, and snippets.

@matheo
Last active May 8, 2019 15:17
Show Gist options
  • Save matheo/1362d8ddd5766ef8d09eb775e572ca90 to your computer and use it in GitHub Desktop.
Save matheo/1362d8ddd5766ef8d09eb775e572ca90 to your computer and use it in GitHub Desktop.
Search DataSource Example
import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { FormControl } from '@angular/forms';
import { SearchDatasource } from '@myproject/model';
@Component({
selector: 'ui-layout-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss'],
encapsulation: ViewEncapsulation.None,
providers: [SearchDatasource]
})
export class SearchComponent implements OnInit, OnDestroy {
control = new FormControl('');
constructor(private source: SearchDatasource) {}
ngOnInit() {
this.source.connect().subscribe(res => console.log('SEARCH RESULT', res));
}
ngOnDestroy() {
this.source.disconnect();
}
onSearch() {
this.source.filter(this.control.value);
}
}
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { doc } from '@myproject/operators';
import { map } from 'rxjs/operators';
import { DocEntity } from '../types';
import { SearchRequest } from './types';
@Injectable({
providedIn: 'root'
})
export class SearchDatabase {
constructor(private api: AngularFirestore) {}
search(args: SearchRequest) {
return this.api
.doc<DocEntity>(`Orders/${args.query}`)
.snapshotChanges()
.pipe(
doc(),
map(order => [order])
);
}
}
import { Injectable } from '@angular/core';
import { DataSourceItem, ReactiveDataSource } from '@matheo/datasource';
import { of, throwError } from 'rxjs';
import { DocEntity } from '../types';
import { SearchDatabase } from './search.database';
import { SearchRequest } from './types';
@Injectable()
export class SearchDatasource extends ReactiveDataSource<
SearchRequest,
Array<DocEntity>,
DocEntity
> {
constructor(protected database: SearchDatabase) {
super();
this.config = {
debug: true,
autoStart: false // wait for query
};
this.pageSize = 7;
}
rawDefault() {
return [];
}
rawFetch(args: SearchRequest) {
return args.query ? this.database.search(args) : throwError(false);
}
rawTotal(result: DocEntity[]) {
return of(result.length);
}
rawResult(result: DocEntity[]): DocEntity[] {
return result;
}
filter(query: string): void {
this.refresh({ query });
}
resFilter(result: DocEntity[]): DataSourceItem[] {
throw new Error('Method not implemented.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment