|
| 1 | +// #docplaster |
| 2 | +// #docregion |
| 3 | +import { Component, OnInit } from '@angular/core'; |
| 4 | +import { Router } from '@angular/router'; |
| 5 | +import { Observable } from 'rxjs/Observable'; |
| 6 | +import { Subject } from 'rxjs/Subject'; |
| 7 | + |
| 8 | +import { HeroSearchService } from './hero-search.service'; |
| 9 | +import { Hero } from './hero'; |
| 10 | + |
| 11 | +@Component({ |
| 12 | + selector: 'hero-search', |
| 13 | + templateUrl: 'app/hero-search.component.html', |
| 14 | + providers: [HeroSearchService] |
| 15 | +}) |
| 16 | +export class HeroSearchComponent implements OnInit { |
| 17 | + // #docregion subject |
| 18 | + search = new Subject<string>(); |
| 19 | + // #enddocregion subject |
| 20 | + // #docregion search |
| 21 | + heroes: Observable<Hero>; |
| 22 | + // #enddocregion search |
| 23 | + |
| 24 | + constructor( |
| 25 | + private heroSearchService: HeroSearchService, |
| 26 | + private router: Router) {} |
| 27 | + |
| 28 | + |
| 29 | + // #docregion search |
| 30 | + ngOnInit() { |
| 31 | + this.heroes = this.search |
| 32 | + .asObservable() // "cast" as Observable |
| 33 | + .debounceTime(300) // wait for 300ms pause in events |
| 34 | + .distinctUntilChanged() // ignore if next search term is same as previous |
| 35 | + .switchMap(term => term // switch to new observable each time |
| 36 | + // return the http search observable |
| 37 | + ? this.heroSearchService.search(term) |
| 38 | + // or the observable of empty heroes if no search term |
| 39 | + : Observable.of<Hero[]>([])) |
| 40 | + |
| 41 | + .catch(error => { |
| 42 | + // Todo: real error handling |
| 43 | + console.log(error); |
| 44 | + return Observable.throw(error); |
| 45 | + }); |
| 46 | + } |
| 47 | + // #enddocregion search |
| 48 | + |
| 49 | + gotoDetail(hero: Hero) { |
| 50 | + let link = ['/detail', hero.id]; |
| 51 | + this.router.navigate(link); |
| 52 | + } |
| 53 | +} |
0 commit comments