]> git.uio.no Git - u/erikhf/frm.git/blobdiff - src/components/search/livesearch.ts
semi working live search
[u/erikhf/frm.git] / src / components / search / livesearch.ts
index 1b94dce95ce667c6aa05f94febe9308dddf7a168..2b3195415a0483eef1b354f1c2169b66e45f4bc4 100644 (file)
@@ -1,12 +1,49 @@
-import {View, CORE_DIRECTIVES} from 'angular2/angular2';
-import {Pipe} from 'angular2/angular2';
+import {Directive, View, EventEmitter, ElementRef} from 'angular2/angular2';
 
+// RxJs
+import * as Rx from '@reactivex/rxjs/dist/cjs/Rx';
 
+import {SearchService} from "./SearchService";
 
-@Pipe({
-    name: 'livesearch'
+declare var zone: Zone;
+
+@Directive({
+    selector: 'input[type=text][mou-live-search]',
+    outputs: ['results', 'loading'],
+    providers: [SearchService]
 })
-export class Livesearch {
-    transform(value, args) { return value * 2; }
+export class LiveSearch {
+    results: EventEmitter = new EventEmitter();
+    loading: EventEmitter = new EventEmitter();
+
+    constructor( private el: ElementRef, public search: SearchService){
+
+    }
+
+    onInit(){
+        console.log("starting");
+        (<any>Rx).Observable.fromEvent(this.el.nativeElement, 'keyup')
+            .map(e => e.target.value)
+            .filter(text => text.length > 2)
+            .debounceTime(250)
+            .distinctUntilChanged()
+            .do(zone.bind(() => this.loading.next(true)))
+            .flatMap(query => this.search.search(query))
+            .do(zone.bind(() => this.loading.next(false)))
+            .subscribe(
+                zone.bind( orgunits => {
+                    //this.results.next(orgunits);
+                    console.log(orgunits);
+                    this.results.next(orgunits);
+                }),
+                zone.bind(err => {
+                    console.log(err);
+                    this.results.next(['ERROR, see console']);
+                }),
+                () => {
+                    console.log("complete");
+                }
+            )
+    }
 }