|
| 1 | +// #docplaster |
| 2 | +// #docregion |
| 3 | +import 'rxjs/add/operator/debounceTime'; |
| 4 | +import 'rxjs/add/operator/distinctUntilChanged'; |
| 5 | +import 'rxjs/add/operator/do'; |
| 6 | +import 'rxjs/add/operator/filter'; |
| 7 | +import 'rxjs/add/operator/switchMap'; |
| 8 | +import 'rxjs/add/observable/merge'; |
| 9 | +import { Component, OnInit, OnDestroy } from '@angular/core'; |
| 10 | +import { FormBuilder, FormGroup } from '@angular/forms'; |
| 11 | +import { Router, ActivatedRoute, Params } from '@angular/router'; |
| 12 | +import { Observable } from 'rxjs/Observable'; |
| 13 | +import { Subject } from 'rxjs/Subject'; |
| 14 | + |
| 15 | +import { HeroService } from './hero.service'; |
| 16 | +import { Hero } from './hero'; |
| 17 | + |
| 18 | +@Component({ |
| 19 | + moduleId: module.id, |
| 20 | + selector: 'hero-search', |
| 21 | + templateUrl: 'hero-search.component.html', |
| 22 | + styleUrls: [ 'hero-search.component.css' ] |
| 23 | +}) |
| 24 | +export class HeroSearchComponent implements OnInit, OnDestroy { |
| 25 | + heroes$: Observable<Hero[]>; |
| 26 | + destroy$: Subject<any> = new Subject(); |
| 27 | + form: FormGroup; |
| 28 | + |
| 29 | + constructor( |
| 30 | + private heroService: HeroService, |
| 31 | + private formBuilder: FormBuilder, |
| 32 | + private route: ActivatedRoute, |
| 33 | + private router: Router |
| 34 | + ) {} |
| 35 | + |
| 36 | + ngOnInit(): void { |
| 37 | + this.form = this.formBuilder.group({ |
| 38 | + searchTerms: [''] |
| 39 | + }); |
| 40 | + |
| 41 | + const searchTerms$: Observable<string> = this.form.valueChanges |
| 42 | + .debounceTime(300) |
| 43 | + .map(model => model.searchTerms); |
| 44 | + |
| 45 | + const querySearch$: Observable<string> = this.route.queryParams |
| 46 | + .map((params: Params) => params['q']) |
| 47 | + .do(searchTerms => this.form.patchValue({ |
| 48 | + searchTerms |
| 49 | + })); |
| 50 | + |
| 51 | + this.heroes$ = Observable.merge(searchTerms$, querySearch$) |
| 52 | + .distinctUntilChanged() |
| 53 | + .takeUntil(this.destroy$) |
| 54 | + .do(q => this.router.navigate(['./'], { queryParams: { q }, relativeTo: this.route })) |
| 55 | + .switchMap(term => term |
| 56 | + ? this.heroService.search(term) |
| 57 | + : Observable.of<Hero[]>([]) |
| 58 | + ) |
| 59 | + .catch(error => { |
| 60 | + return Observable.of<Hero[]>([]); |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + ngOnDestroy() { |
| 65 | + this.destroy$.next(); |
| 66 | + } |
| 67 | +} |
0 commit comments