]> git.uio.no Git - u/erikhf/frm.git/blob - src/components/search/livesearch.ts
2b3195415a0483eef1b354f1c2169b66e45f4bc4
[u/erikhf/frm.git] / src / components / search / livesearch.ts
1 import {Directive, View, EventEmitter, ElementRef} from 'angular2/angular2';
2
3 // RxJs
4 import * as Rx from '@reactivex/rxjs/dist/cjs/Rx';
5
6 import {SearchService} from "./SearchService";
7
8 declare var zone: Zone;
9
10 @Directive({
11     selector: 'input[type=text][mou-live-search]',
12     outputs: ['results', 'loading'],
13     providers: [SearchService]
14 })
15 export class LiveSearch {
16     results: EventEmitter = new EventEmitter();
17     loading: EventEmitter = new EventEmitter();
18
19     constructor( private el: ElementRef, public search: SearchService){
20
21     }
22
23     onInit(){
24         console.log("starting");
25         (<any>Rx).Observable.fromEvent(this.el.nativeElement, 'keyup')
26             .map(e => e.target.value)
27             .filter(text => text.length > 2)
28             .debounceTime(250)
29             .distinctUntilChanged()
30             .do(zone.bind(() => this.loading.next(true)))
31             .flatMap(query => this.search.search(query))
32             .do(zone.bind(() => this.loading.next(false)))
33             .subscribe(
34                 zone.bind( orgunits => {
35                     //this.results.next(orgunits);
36                     console.log(orgunits);
37                     this.results.next(orgunits);
38                 }),
39                 zone.bind(err => {
40                     console.log(err);
41                     this.results.next(['ERROR, see console']);
42                 }),
43                 () => {
44                     console.log("complete");
45                 }
46             )
47     }
48 }
49