Skip to content

Instantly share code, notes, and snippets.

@dreamerkumar
Created September 22, 2016 19:57
Show Gist options
  • Save dreamerkumar/37817361a0467dc7335c8ff4fbb65d0a to your computer and use it in GitHub Desktop.
Save dreamerkumar/37817361a0467dc7335c8ff4fbb65d0a to your computer and use it in GitHub Desktop.
angular 2 autocomplete service using rxjs
import {Injectable} from '@angular/core';
import { URLSearchParams, Jsonp } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class WikipediaSearchService {
constructor(private jsonp: Jsonp, private url: string) { }
search(terms: Observable<string>, debounceMs = 400) {
return terms.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.rawSearch(term));
}
rawSearch(term: string) {
let search = new URLSearchParams();
search.set('action', 'opensearch');
search.set('search', term);
search.set('format', 'json');
return this.jsonp.get(this.url)
.map(response => response.json()[1]);
}
}